/**
 * 问题排查 API
 */
import http from '@/utils/http'
import { createSSE } from '@/utils/sse'
import type {
  TroubleshootRequest,
  TroubleshootResponse,
  SearchRequest,
  SearchResponse,
  AnalyzeRequest,
  AnalyzeResponse,
  HealthResponse,
  CacheStatsResponse,
  CacheClearResponse,
  ExportRequest,
  SubmitRequest,
  SubmitResponse,
  AnalyzeStreamEvent,
  ProductsResponse,
  ProductResponse,
  DocumentsResponse,
  FAQsResponse,
} from '@/types/troubleshoot'
import type { ProjectsResponse, CategoriesResponse } from '@/types/api'

/** 完整排查流程 */
export async function troubleshoot(data: TroubleshootRequest): Promise<TroubleshootResponse> {
  const res = await http.post<TroubleshootResponse>('/api/troubleshoot', data)
  return res.data
}

/** 搜索匹配案例 */
export async function search(data: SearchRequest): Promise<SearchResponse> {
  const res = await http.post<SearchResponse>('/api/search', data)
  return res.data
}

/** AI 深度分析 */
export async function analyze(data: AnalyzeRequest): Promise<AnalyzeResponse> {
  const res = await http.post<AnalyzeResponse>('/api/analyze', data)
  return res.data
}

/** 流式 AI 分析（SSE） */
export function analyzeStream(
  params: {
    project_name?: string
    system_type?: string
    apk_product?: string
    query: string
    model?: string
  },
  handlers: Record<string, (data: AnalyzeStreamEvent) => void>,
  onError?: (error: Event) => void
) {
  return createSSE({
    url: '/api/analyze/stream',
    params: params as Record<string, string>,
    handlers,
    onError,
  })
}

/** 健康检查 */
export async function health(): Promise<HealthResponse> {
  const res = await http.get<HealthResponse>('/api/health')
  return res.data
}

/** 获取项目列表 */
export async function getProjects(): Promise<ProjectsResponse> {
  const res = await http.get<ProjectsResponse>('/api/projects')
  return res.data
}

/** 获取分类列表 */
export async function getCategories(): Promise<CategoriesResponse> {
  const res = await http.get<CategoriesResponse>('/api/categories')
  return res.data
}

/** 获取缓存统计 */
export async function getCacheStats(): Promise<CacheStatsResponse> {
  const res = await http.get<CacheStatsResponse>('/api/cache/stats')
  return res.data
}

/** 清除缓存 */
export async function clearCache(): Promise<CacheClearResponse> {
  const res = await http.post<CacheClearResponse>('/api/cache/clear')
  return res.data
}

/** 导出 Word 报告 */
export async function exportReport(data: ExportRequest): Promise<Blob> {
  const res = await http.post('/api/export', data, {
    responseType: 'blob',
  })
  return res.data
}

/** 提交问题记录 */
export async function submitRecord(data: SubmitRequest): Promise<SubmitResponse> {
  const res = await http.post<SubmitResponse>('/api/submit', data)
  return res.data
}

// ============================================================
// 产品相关 API（离线模式）
// ============================================================

/** 获取产品列表 */
export async function getProducts(): Promise<ProductsResponse> {
  const res = await http.get('/api/troubleshoot/products')
  return res.data
}

/** 获取产品详情 */
export async function getProduct(productId: string): Promise<ProductResponse> {
  const res = await http.get(`/api/troubleshoot/products/${productId}`)
  return res.data
}

/** 获取产品资料列表 */
export async function getProductDocuments(productId: string): Promise<DocumentsResponse> {
  const res = await http.get(`/api/troubleshoot/products/${productId}/documents`)
  return res.data
}

/** 下载文档 */
export function downloadDocument(docId: string): string {
  return `/api/troubleshoot/documents/${docId}/download`
}

/** 获取产品常见问题 */
export async function getProductFAQs(productId: string, limit?: number): Promise<FAQsResponse> {
  const params = limit ? { limit } : {}
  const res = await http.get(`/api/troubleshoot/products/${productId}/faqs`, { params })
  return res.data
}

/** 上传文档（管理员） */
export async function uploadDocument(productId: string, file: File): Promise<{ success: boolean; doc_id?: string; message?: string }> {
  const formData = new FormData()
  formData.append('product_id', productId)
  formData.append('file', file)
  const res = await http.post('/api/troubleshoot/documents/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return res.data
}

/** 删除文档（管理员） */
export async function deleteDocument(docId: string): Promise<{ success: boolean; message?: string }> {
  const res = await http.delete(`/api/troubleshoot/documents/${docId}/delete`)
  return res.data
}