import axios from 'axios'
import type { 
  UploadResponse, 
  AnalyzeOptions, 
  AnalyzeResponse, 
  SaveRequest, 
  SaveResponse,
  ImageSize
} from '@/types'

const api = axios.create({
  baseURL: '/api',
  timeout: 60000
})

/**
 * 上传文件并分析
 */
export async function uploadFiles(
  jsonFile: File, 
  imageFile: File
): Promise<UploadResponse> {
  const formData = new FormData()
  formData.append('json_file', jsonFile)
  formData.append('image_file', imageFile)
  
  const response = await api.post<UploadResponse>('/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  
  return response.data
}

/**
 * 重新分析结构
 */
export async function reanalyzeStructure(
  request: {
    ocr_data: Record<string, unknown>
    image_size: ImageSize
    options?: AnalyzeOptions
  }
): Promise<AnalyzeResponse> {
  const response = await api.post<AnalyzeResponse>('/analyze', {
    ocr_data: request.ocr_data,
    image_size: request.image_size,
    ...request.options
  })
  
  return response.data
}

/**
 * 保存结果
 */
export async function saveResult(request: SaveRequest): Promise<SaveResponse> {
  const response = await api.post<SaveResponse>('/save', request)
  return response.data
}

/**
 * 健康检查
 */
export async function healthCheck(): Promise<{ status: string }> {
  const response = await api.get('/health')
  return response.data
}

/**
 * 通过文件路径加载数据
 */
export async function loadByPath(
  imagePath: string,
  jsonPath: string,
  outputDir: string = './output',
  structureSuffix: string = '_structure',
  imageSuffix: string = ''
): Promise<UploadResponse> {
  const response = await api.post<UploadResponse>('/load-by-path', {
    image_path: imagePath,
    json_path: jsonPath,
    output_dir: outputDir,
    structure_suffix: structureSuffix,
    image_suffix: imageSuffix
  })
  return response.data
}
