import { get, post, del, downloadFile } from './base'

// 推荐智能体
export const getRecommendedApps = () => {
  return get('/business/apps/recommended')
}

// 热门智能体
export const getHottestApps = () => {
  return get('/business/apps/hottest')
}

// 最新智能体
export const getLatestApps = () => {
  return get('/business/apps/latest')
}

// 系统智能体（Agent Pro）列表
//   GET /business/agent-pros
//   响应字段: id, source_type, source_app_id, name, description, mode,
//            icon_type, icon, icon_background, logo, recommend_score,
//            request_method, request_url, request_headers, request_body_template,
//            parameter_schema, external_config, created_at, updated_at
export const getAgentPros = () => {
  return get('/business/agent-pros')
}

// 当前用户的推荐智能体(混合类型:app / agent_pro)
//   GET /business/apps/my-recommended
//   响应字段(BusinessMixedAgentResponse):
//     target_type: "app" | "agent_pro"
//     target_id:   智能体 id(可能为 app id 或 agent_pro id)
//     name, description, mode, icon_type, icon, icon_background,
//     source_type / source_name / source_app_id (agent_pro 才有),
//     logo, marked_at, created_at, updated_at
//   返回最多 10 条:用户标记的优先,然后用 recommend_score 排序的 agent_pro 补足
export const getMyRecommendedApps = () => {
  return get('/business/apps/my-recommended')
}

// ===== 智能体标记 / 取消标记 =====
//   单个用户最多标记 10 个智能体(BUSINESS_AGENT_MARK_LIMIT)
//   target_type: 'app' | 'agent_pro'

// 列出当前用户已标记的智能体
//   GET /business/agent-marks
export const getAgentMarks = () => {
  return get('/business/agent-marks')
}

// 标记智能体
//   POST /business/agent-marks
//   body: { target_type: 'app' | 'agent_pro', target_id: string(uuid) }
//   返回: { result, status: 'marked', mark: BusinessMixedAgentResponse }
//   错误码: mark-limit-exceeded (已超过 10 个)
export const markAgent = ({ target_type, target_id }) => {
  return post('/business/agent-marks', { target_type, target_id })
}

// 取消标记智能体
//   DELETE /business/agent-marks/<target_type>/<target_id>
//   返回: { result: 'success', status: 'unmarked' }
export const unmarkAgent = ({ target_type, target_id }) => {
  return del(`/business/agent-marks/${target_type}/${target_id}`)
}

// 平台已上架智能体列表（带热度，可选标签过滤）
export const getBusinessAppsList = (params = {}) => {
  return get('/business/apps/list', params)
}

// 检查智能体 API Key 权限（用于判断是否可进入执行页）
export const getAppApiKey = (appId) => {
  return get(`/business/apps/${appId}/api-key`)
}

// 获取智能体详情（执行页用）
export const getAppDetail = (appId) => {
  return get(`/apps/${appId}`)
}

// 智能体基本信息（含 version / version_description / introduction / app_permission / is_listed）
export const getAppBasicInfo = (appId) => {
  return get(`/business/apps/${appId}/basic-info`)
}

// 获取当前用户对该智能体的权限与最新申请进度
export const getAccessStatus = (appId) => {
  return get(`/business/apps/${appId}/access-status`)
}

// 提交智能体使用申请
export const createAccessRequest = (appId, reason) => {
  return post(`/business/apps/${appId}/access-requests`, { reason })
}

// ===== 历史会话 =====

// 当前用户的 API 会话列表(后端按 updated_at desc 排序)
//   GET /business/conversations?page=1&limit=10
//   响应字段(BusinessConversationResponse):
//     id, app_id, app_name, name, summary, status, mode,
//     from_source, from_end_user_id, from_end_user_session_id,
//     message_count, created_at, updated_at
//   返回: { data:[...], page, limit, total, has_more }
//
// 注意:后端 pydantic 在 Query 解析失败时(可能因 Flask-RESTX 的 args 序列化触发 list 形态),
//   会报 "Input should be a valid integer [type=int_type, input_value=['1']]" 错误。
//   解决方案:不传 page/limit(让后端用 default 兜底 page=1/limit=10),完全跳过 Query 解析。
//   后续如果需要分页,在前端用 query 字符串形式手动传,不要用对象。
export const getBusinessConversations = (params = {}) => {
  // 不传 page/limit(让后端 pydantic 用 default 兜底 page=1/limit=10),
  // 避免后端 Query 解析触发 "Input should be a valid integer [type=int_type, input_value=['1']]"
  // 错误(已知后端 bug,Flask-RESTX args 序列化时会把值序列化成 list 形态)。
  // 后续如需分页:在 schema 把 page/limit 标为 Optional,或后端改成 from_request 直接读 dict。
  void params // 暂忽略,保持接口签名兼容
  return get('/business/conversations')
}

// 单个会话的详情(带分页消息轮次)
//   GET /business/conversations/<conversation_id>?page=1&limit=10
//   响应: { conversation: {...}, messages: [...], page, limit, total, has_more }
//   每条消息字段(BusinessConversationMessageResponse):
//     id, conversation_id, query, answer, status, error,
//     workflow_run_id, parent_message_id, created_at, updated_at
export const getBusinessConversationDetail = (conversationId, params = {}) => {
  return get(`/business/conversations/${conversationId}`, params)
}

// 下载单条消息的文档(Word / PDF)
//   GET /business/messages/<message_id>/content/download?format=word|pdf
//   后端 BusinessMessageContentDownloadQuery.format: Literal['word', 'pdf'],默认 word
//   返回: send_file(... as_attachment=True, download_name='message-XXXXXXXX.{docx|pdf}')
//   这里用 base.downloadFile 直接走 fetch(不走 JSON 解析),返回 { blob, filename }
//
// 注意:后端 pydantic Literal 类型在 query 解析失败时(Flask-RESTX args 序列化成 list 形态),
//   会报 "Input should be 'word' or 'pdf' [type=literal_error, input_value=['word']]"。
//   解决:format=word(默认)时**不传 query**,让后端用 default 兜底,完全跳过 query 解析;
//        format=pdf 时再显式传,绕不开时才走 query(由后端 Literal 校验)。
export const downloadMessageContent = async (messageId, format = 'word') => {
  const safeFormat = format === 'pdf' ? 'pdf' : 'word'
  const url = safeFormat === 'word'
    ? `/business/messages/${messageId}/content/download`
    : `/business/messages/${messageId}/content/download?format=${safeFormat}`
  return downloadFile(url)
}
