import { get, post, put, del } from '../request'
import type { FineTuneStartPayload, FineTuneTask, TrainingProgress, LogContent } from '@/types'

export interface TrainingDiagnostic {
  level: string
  title: string
  suggestion: string
}

export interface FineTunePreflightResult {
  valid: boolean
  errors: string[]
  warnings: string[]
  diagnostics?: TrainingDiagnostic[]
  node?: {
    id?: string
    code?: string
    name?: string
    api_base_url?: string
    scheduler_status?: string
    gpu_count?: number
  }
  job_payload?: Record<string, unknown>
  preview?: {
    command?: string[]
    command_text?: string
    work_dir?: string
    path_checks?: Array<Record<string, unknown>>
    accelerator?: Record<string, unknown>
    runtime_files?: Array<Record<string, unknown>>
  }
  sync_results?: Array<Record<string, unknown>>
}

/** 训练任务列表 */
export const getFineTuneList = () => get<FineTuneTask[]>('/fine-tune')

/** 训练任务详情 */
export const getFineTune = (id: string | number) => get<FineTuneTask>(`/fine-tune/${id}`)

/** 任务名查重 */
export const checkFineTuneName = (name: string) =>
  get<{ exists: boolean }>('/fine-tune/check-name', { name })

/** 创建训练任务记录（第一步） */
export const createFineTune = (data: Partial<FineTuneTask>) =>
  post<{ id: string | number }>('/fine-tune', data)

/** 启动训练（第二步） */
export const startFineTune = (data: FineTuneStartPayload) => post('/fine-tune/start', data)

/** 创建前训练预检，不落库 */
export const preflightFineTune = (data: Omit<FineTuneStartPayload, 'task_id'>) =>
  post<FineTunePreflightResult>('/fine-tune/preflight', data)

/** 创建前真实命令预览，不落库 */
export const previewFineTuneCommand = (data: Omit<FineTuneStartPayload, 'task_id'>) =>
  post<FineTunePreflightResult>('/fine-tune/command-preview', data)

/** 训练失败诊断 */
export const getFineTuneDiagnostics = (id: string | number) =>
  get<{ task_id: string | number; status?: string; failure_reason?: string; diagnostics: TrainingDiagnostic[] }>(`/fine-tune/${id}/diagnostics`)

/** 更新训练任务 */
export const updateFineTune = (id: string | number, data: Partial<FineTuneTask>) =>
  put(`/fine-tune/${id}`, data)

/** 停止训练任务 */
export const stopFineTune = (id: string | number) => post(`/fine-tune/stop/${id}`)

/** 删除训练任务 */
export const deleteFineTune = (id: string | number) => del(`/fine-tune/${id}`)

/** 获取训练进度 */
export const getFineTuneProgress = (id: string | number) =>
  get<TrainingProgress>(`/fine-tune/progress/${id}`)

export const getFineTuneLogs = (
  id: string | number,
  params: { tail_lines?: number; offset?: number; limit?: number } = {},
) => get<LogContent & { job_id?: string; source?: string }>(`/fine-tune/${id}/logs`, params)

/** 启动 TensorBoard */
export const startTensorboard = () => post('/fine-tune/tensorboard/start')

/** 提交 Web 日志 */
export const sendWebLog = (level: string, message: string, page: string) =>
  post('/web-log', { level, message, page, timestamp: new Date().toISOString() })
