import apiClient from './client'

// ============= 前端卡类型 =============

/**
 * 前端卡：存储在角色卡 extensions.frontend_card 中的 HTML/JS 面板。
 * 在聊天界面中固定显示，内容完全由卡作者自定义。
 */
export interface FrontendCard {
  html: string
  enabled?: boolean
  /** 显示位置：顶部（默认）或底部 */
  position?: 'top' | 'bottom'
}

/**
 * 从角色卡 extensions 中提取前端卡配置。
 * 支持多种常见格式：
 *  - extensions.frontend_card.html（本平台标准格式）
 *  - extensions.frontend_card（字符串，直接就是 HTML）
 *  - extensions.chara_card_ui（字符串，ST 社区常见格式）
 */
export function extractFrontendCard(extensions: Record<string, any> | null | undefined): FrontendCard | null {
  if (!extensions) return null

  // 标准格式：extensions.frontend_card 是对象
  const fc = extensions['frontend_card']
  if (fc) {
    if (typeof fc === 'string' && fc.trim()) {
      return { html: fc, enabled: true, position: 'top' }
    }
    if (typeof fc === 'object' && typeof fc.html === 'string' && fc.html.trim()) {
      return {
        html: fc.html,
        enabled: fc.enabled !== false,
        position: fc.position === 'bottom' ? 'bottom' : 'top',
      }
    }
  }

  // 兼容格式：extensions.chara_card_ui（ST 社区卡常用）
  const charaCardUi = extensions['chara_card_ui']
  if (typeof charaCardUi === 'string' && charaCardUi.trim()) {
    return { html: charaCardUi, enabled: true, position: 'top' }
  }

  return null
}

// ============= 角色卡类型定义 =============

export interface Character {
  id: number
  name: string
  avatar: string
  creator: string
  version: string
  description: string
  personality: string
  scenario: string
  firstMes: string
  mesExample: string
  creatorNotes: string
  systemPrompt: string
  postHistoryInstructions: string
  tags: string[]
  alternateGreetings: string[]
  characterBook: Record<string, any>
  extensions: Record<string, any>
  spec: string
  specVersion: string
  isPublic: boolean
  useCount: number
  favoriteCount: number
  createdAt: string
  updatedAt: string
}

export interface CreateCharacterRequest {
  name: string
  avatar?: string
  creator?: string
  version?: string
  description?: string
  personality?: string
  scenario?: string
  firstMes?: string
  mesExample?: string
  creatorNotes?: string
  systemPrompt?: string
  postHistoryInstructions?: string
  tags?: string[]
  alternateGreetings?: string[]
  characterBook?: Record<string, any>
  extensions?: Record<string, any>
  isPublic?: boolean
}

export interface UpdateCharacterRequest {
  name?: string
  avatar?: string
  creator?: string
  version?: string
  description?: string
  personality?: string
  scenario?: string
  firstMes?: string
  mesExample?: string
  creatorNotes?: string
  systemPrompt?: string
  postHistoryInstructions?: string
  tags?: string[]
  alternateGreetings?: string[]
  characterBook?: Record<string, any> | null
  extensions?: Record<string, any>
  isPublic?: boolean
}

export interface GetCharacterListRequest {
  page?: number
  pageSize?: number
  keyword?: string
  tag?: string
  isPublic?: boolean
}

export interface CharacterListResponse {
  list: Character[]
  total: number
  page: number
  pageSize: number
}

// API 方法
export const characterApi = {
  // 创建角色卡
  createCharacter: (data: CreateCharacterRequest): Promise<{ data: Character }> => {
    return apiClient.post('/app/character', data)
  },

  // 获取角色卡列表
  getCharacterList: (params?: GetCharacterListRequest): Promise<{ data: CharacterListResponse }> => {
    return apiClient.get('/app/character', { params })
  },

  // 获取角色卡详情
  getCharacterById: (id: number): Promise<{ data: Character }> => {
    return apiClient.get(`/app/character/${id}`)
  },

  // 更新角色卡
  updateCharacter: (id: number, data: UpdateCharacterRequest) => {
    return apiClient.put(`/app/character/${id}`, data)
  },

  // 删除角色卡
  deleteCharacter: (id: number) => {
    return apiClient.delete(`/app/character/${id}`)
  },

  // 上传角色卡文件（PNG/JSON）
  uploadCharacter: (file: File): Promise<{ data: Character }> => {
    const formData = new FormData()
    formData.append('file', file)
    return apiClient.post('/app/character/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
  },

  // 导出角色卡为 JSON
  exportCharacter: (id: number) => {
    return apiClient.get(`/app/character/${id}/export`, {
      responseType: 'blob',
    })
  },
}
