import type { SourceFileExtractionStatus, SourceFileRecord } from '@/types';

export interface SourceFileExtractionStatusView {
  label: string;
  detail: string;
  badgeClassName: string;
}

type SourceFileExtractionStatusInput = Pick<
  SourceFileRecord,
  'extraction_status'
  | 'extraction_model'
  | 'extraction_summary'
  | 'extraction_error'
  | 'extracted_material_count'
  | 'extracted_at'
>;

const STATUS_VIEW: Record<SourceFileExtractionStatus, Omit<SourceFileExtractionStatusView, 'label' | 'detail'> & { label: string }> = {
  uploaded: {
    label: '仅附件',
    badgeClassName: 'border-slate-200 bg-slate-50 text-slate-700',
  },
  local_parsed: {
    label: '本地解析',
    badgeClassName: 'border-emerald-200 bg-emerald-50 text-emerald-700',
  },
  llm_processing: {
    label: '识别中',
    badgeClassName: 'border-blue-200 bg-blue-50 text-blue-700',
  },
  llm_succeeded: {
    label: '识别成功',
    badgeClassName: 'border-emerald-200 bg-emerald-50 text-emerald-700',
  },
  llm_failed: {
    label: '识别失败',
    badgeClassName: 'border-red-200 bg-red-50 text-red-700',
  },
};

function countSuffix(count: number | null | undefined): string {
  return typeof count === 'number' && Number.isFinite(count) ? ` ${count} 项` : '';
}

export function describeSourceFileExtractionStatus(
  record: SourceFileExtractionStatusInput,
): SourceFileExtractionStatusView {
  const status = record.extraction_status ?? 'uploaded';
  const base = STATUS_VIEW[status] ?? STATUS_VIEW.uploaded;

  if (status === 'llm_succeeded') {
    return {
      ...base,
      label: `${base.label}${countSuffix(record.extracted_material_count)}`,
      detail: record.extraction_summary || 'GLM 识别已完成',
    };
  }

  if (status === 'local_parsed') {
    return {
      ...base,
      label: `${base.label}${countSuffix(record.extracted_material_count)}`,
      detail: record.extraction_summary || 'Excel 已本地解析',
    };
  }

  if (status === 'llm_failed') {
    return {
      ...base,
      detail: record.extraction_error || '识别失败，附件已保留',
    };
  }

  if (status === 'llm_processing') {
    return {
      ...base,
      detail: record.extraction_model ? `模型：${record.extraction_model}` : '等待识别结果',
    };
  }

  return {
    ...base,
    detail: '文件已上传，未进入识别流程',
  };
}
