/**
 * 全局业务类型定义
 */

/** 通用分页/列表响应暂用数组，后端未分页 */

// ============ 模型管理 ============
export type ModelType = 'LLM' | 'CV' | 'NLP' | 'Embedding' | 'Other'
export type ModelPurpose = 'training' | 'inference' | 'evaluation'
export type ModelSource = 'local' | 'api' | 'online'

export interface TrainMethod {
  name: string
}

/** 数据库配置模型 */
export interface ModelItem {
  id: number | string
  name: string
  type: ModelType | string
  purpose: ModelPurpose | string
  model_source: ModelSource | string
  description?: string
  path?: string
  api_url?: string
  api_key?: string
  online_model_name?: string
  create_time?: string
}

/** 已训练模型 */
export interface TrainedModel {
  id: number | string
  name: string
  train_methods?: TrainMethod[]
  base_model_path?: string
  create_time?: string
  merged?: boolean
  merging?: boolean
  merged_path?: string
}

/** 创建/编辑模型请求体 */
export interface ModelForm {
  id?: number | string
  name: string
  type: ModelType | string
  purpose: ModelPurpose | string
  model_source: ModelSource | string
  description?: string
  path?: string
  api_url?: string
  api_key?: string
  online_model_name?: string
}

// ============ 数据集 ============
export type DatasetType = 'train' | 'test' | 'eval' | 'val' | 'other'
export type DatasetStorage = 'local' | 'cloud' | 'minio'
export type DatasetSource = 'upload' | 'task'

export interface DatasetFile {
  id?: string
  name: string
  size?: string | number
  [k: string]: any
}

export interface DatasetItem {
  id: number | string
  name: string
  type: DatasetType | string
  storage_type: DatasetStorage | string
  source?: DatasetSource
  task_id?: string | number
  size?: string | number
  count?: number
  description?: string
  create_time?: string
  files?: DatasetFile[]
}

export interface DatasetVersion {
  id: string
  version: number
  create_time: string
  description?: string
}

export interface DatasetVersionList {
  versions: DatasetVersion[]
  active_version_id: string
  next_version_number?: number
}

// ============ 训练任务 ============
export type TrainType = 'SFT' | 'DPO' | 'CPT'
export type TrainMethodType = 'lora' | 'full'
export type TaskStatus = 'pending' | 'running' | 'completed' | 'failed' | string

export interface FineTuneTask {
  id: number | string
  name: string
  description?: string
  status: TaskStatus
  train_type: TrainType | string
  train_method?: TrainMethodType | string
  template?: string
  base_model: number | string
  train_dataset_id?: number | string
  auto_merge?: boolean
  output_model_name?: string
  gpus?: number[]
  batch_size?: number
  learning_rate?: number
  n_epochs?: number
  save_steps?: number
  lr_scheduler_type?: string
  max_length?: number
  warmup_ratio?: number
  weight_decay?: number
  lora_alpha?: number
  lora_dropout?: number
  lora_rank?: number
  /** 训练时量化位数（QLoRA）：0=不量化 / 8 / 4 */
  quantization_bit?: number
  /** 训练完成后是否导出量化模型 */
  export_quantized?: boolean
  /** 导出量化方法：bnb / gptq / awq / gguf */
  quant_method?: 'bnb' | 'gptq' | 'awq' | 'gguf' | string
  /** 导出量化位数 */
  quant_bits?: number
  /** 分组大小（GPTQ / AWQ） */
  quant_group_size?: number
  /** GGUF 导出格式 */
  export_format?: string
  progress?: number
  process_id?: number
  train_duration?: string
  create_time?: string
}

export type FineTuneStartPayload = Omit<
  FineTuneTask,
  'id' | 'status' | 'progress' | 'process_id' | 'train_duration' | 'create_time'
> & {
  task_id: string | number
  description: string
  template: string
  train_method: TrainMethodType
  train_dataset_id: string | number
  auto_merge: boolean
  output_model_name: string
  gpus: number[]
  batch_size: number
  learning_rate: number
  n_epochs: number
  save_steps: number
  lr_scheduler_type: string
  max_length: number
  warmup_ratio: number
  weight_decay: number
  lora_alpha: number
  lora_dropout: number
  lora_rank: number
  quantization_bit: number
  export_quantized: boolean
  quant_method: string
  quant_bits: number
  quant_group_size: number
  export_format: string
}

export interface TrainingProgress {
  status?: string
  progress?: number
  step?: string
  speed?: string
  eta?: string
}

// ============ 模型推理 / 对比 (model-compare) ============
export interface LoadedModel {
  model_id?: number | string
  model_name?: string
  status?: string
  pid?: number
  port?: number
}

export interface CompareTask {
  id: number | string
  model_name?: string
  name?: string
  description?: string
  status?: string
  models?: CompareModelRef[] | string
  load_status?: string | { loaded_models: LoadedModel[] }
  create_time?: string
}

export interface CompareModelRef {
  model_id: number | string
  model_name: string
  model_path: string
  gpu_id: number
  source?: string
  port?: number
}

// ============ 模型评测 ============
export type EvalType = 'custom' | 'baseline'
export type DimensionType = 'classification' | 'metric' | 'text_similarity'
export type EvalErrorType = '混淆' | '不完整' | '格式偏差' | '幻觉' | '其他'

export interface EvalTask {
  id: number | string
  eval_task_name?: string
  model_name?: string
  model_id?: number | string
  dataset?: string
  metric?: string
  score?: number
  status?: string
  create_time?: string
}

/** 启动评测时提交的可选基础指标配置。 */
export interface BasicEvalMetricsConfig {
  bleu: {
    enabled: boolean
    ngram: number
  }
  rouge: {
    enabled: boolean
    methods: string[]
  }
  cosine: {
    enabled: boolean
  }
  output_precision: number
}

export interface StartEvalPayload {
  eval_task_name: string
  eval_type: EvalType
  model_id: string | number
  gpu_id: string | number
  dataset_id: string | number
  dimension_id: string | number
  data_source: 'dataset' | 'inference'
  leaderboard: boolean
  basic_metrics: BasicEvalMetricsConfig
}

/** 单个测试样本的评测结果 */
export interface EvalSampleResult {
  id: number | string
  index: number
  input: string
  reference_answer?: string
  model_output: string
  score: number | null
  max_score?: number
  passed?: boolean
  status: 'completed' | 'pending' | 'failed'
  judgement?: '正确' | '部分正确' | '错误'
  evaluation_reason?: string
  error_type?: EvalErrorType
  dimension_scores?: Array<{
    name: string
    score: number
    max_score: number
  }>
}

/** 评测任务详情，包含逐样本结果和综合评价 */
export interface EvalTaskDetail extends EvalTask {
  evaluator_model?: string
  sample_count: number
  completed_count: number
  passed_count?: number
  completed_time?: string
  overall_score: number
  overall_score_max: number
  overall_evaluation: string
  improvement_suggestions: string[]
  dimension_summary: Array<{
    name: string
    score: number
    max_score: number
    pass_rate: number
  }>
  samples: EvalSampleResult[]
}

export interface Dimension {
  id: number | string
  name: string
  type: DimensionType | string
  description?: string
  eval_model?: string
  eval_method?: string | string[]
  eval_prompt?: string
  is_active?: boolean
  is_default?: boolean
  bleu_n?: number
  output_precision?: number
  score_min?: number
  score_max?: number
  pass_threshold?: number
  create_time?: string
}

// ============ 系统监控 ============
export interface GpuProcess {
  pid: number
  name: string
  memory_used_gb: number
  task_name?: string
  user?: string
}

export interface GpuInfo {
  name: string
  gpu_percent: number
  memory_used_gb: number
  memory_total_gb: number
  temperature: number
  power_w: number
  id?: number
  uuid?: string
  status?: 'idle' | 'busy' | 'warning' | 'offline'
  memory_percent?: number
  power_limit_w?: number
  processes?: GpuProcess[]
  fan_speed?: number
  clock_mhz?: number
  driver_version?: string
}

export interface SystemInfo {
  timestamp?: string
  cpu?: {
    percent: number
    cores: number
    percents?: number[]
    model?: string
    frequency_mhz?: number
    load_1m?: number
  }
  memory?: {
    used_gb: number
    total_gb: number
    percent: number
    available_gb: number
    cached_gb: number
  }
  disk?: {
    used_gb: number
    total_gb: number
    percent: number
    read_mb_s?: number
    write_mb_s?: number
  }
  gpu?: GpuInfo[]
  network?: {
    download_mb?: number
    upload_mb?: number
    download_mb_s?: number
    upload_mb_s?: number
  }
  system?: {
    uptime_seconds?: number
    process_count?: number
    os?: string
  }
}

export interface HealthMetrics {
  cpu_percent?: number
  memory_percent?: number
  disk_percent?: number
}

// ============ 用户与权限 ============
/** 页面级权限编码，与路由模块保持一一对应 */
export type PermissionCode =
  | 'dashboard'
  | 'fine-tune'
  | 'model-eval'
  | 'model-inference'
  | 'model-manage'
  | 'dataset'
  | 'data-process'
  | 'data-convert'
  | 'compute'
  | 'hardware'
  | 'logs'
  | 'user-settings'

export type UserRole = 'admin' | 'operator' | 'viewer'

export type UserStatus = 'active' | 'disabled'

export interface SystemUser {
  id: string
  username: string
  display_name: string
  role: UserRole
  status: UserStatus
  permissions: PermissionCode[]
  create_time: string
  last_login?: string
  protected?: boolean
}

export interface LoginResponse {
  token: string
  user: SystemUser
}

export interface CreateUserPayload {
  username: string
  display_name: string
  password: string
  role: UserRole
  status?: UserStatus
  permissions?: PermissionCode[]
}

export interface UpdateUserAccessPayload {
  role?: UserRole
  status?: UserStatus
  permissions?: PermissionCode[]
}

// ============ 日志 ============
export interface LogFile {
  file: string
  name: string
  size: string
  pid?: number
  date?: string
}

export interface LogContent {
  content: string
  file: string
  size: string
}

export interface TrainingLogFile extends LogFile {
  pid?: number
}

// ============ 其他工具 ============
export interface CustomTool {
  id: string
  name: string
  description: string
  url: string
  icon: string
}
