/**
 * ============================================================
 * documentExtractionService.ts — 文档提取前端 service
 * ============================================================
 * 调用后端 /api/extract-materials 端点，将非 Excel 文件转换并提取物料。
 * ============================================================
 */

import type { ParsedMaterialRow } from '@/lib/materialImportParser';

const DEFAULT_AUTOMATION_PORT = '3030';

function resolveAutomationBaseUrl(): string {
  const explicit = (import.meta.env.VITE_AUTOMATION_BASE_URL as string | undefined)?.trim();
  if (explicit) return explicit.replace(/\/+$/, '');
  if (import.meta.env.DEV) return '';

  const port = (import.meta.env.VITE_AUTOMATION_PORT as string | undefined) ?? DEFAULT_AUTOMATION_PORT;
  if (typeof window !== 'undefined') {
    return `${window.location.protocol}//${window.location.hostname}${port ? `:${port}` : ''}`;
  }
  return `http://127.0.0.1:${port}`;
}

const BASE_URL = resolveAutomationBaseUrl();

export interface DocumentExtractionResult {
  items: ParsedMaterialRow[];
  summary: string;
  markdownLength: number;
  elapsed: string;
}

/**
 * 上传文件到后端，执行 markitdown 转换 + LLM 提取物料。
 * 返回提取出的 `ParsedMaterialRow[]`，与 Excel 解析结果格式一致，
 * 可直接传入 `buildUploadedMaterialInput()` + `createMaterials()`。
 */
export async function extractMaterialsFromDocument(
  file: File,
  batchId: string,
): Promise<DocumentExtractionResult> {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('batch_id', batchId);
  formData.append('source_file_name', file.name);

  const res = await fetch(`${BASE_URL}/api/extract-materials`, {
    method: 'POST',
    body: formData,
  });

  if (!res.ok) {
    let errorMsg: string;
    try {
      const body = await res.json() as { error?: string };
      errorMsg = body.error || `服务端错误 (${res.status})`;
    } catch {
      errorMsg = `服务端错误 (${res.status}): ${res.statusText}`;
    }
    throw new Error(`文档提取失败: ${errorMsg}`);
  }

  const body = await res.json() as {
    success: boolean;
    items: Array<Record<string, string>>;
    summary: string;
    markdownLength: number;
    elapsed: string;
    error?: string;
  };

  if (!body.success) {
    throw new Error(`文档提取失败: ${body.error || '未知错误'}`);
  }

  // 将后端返回的 RawCsvRow 格式 items 转为 ParsedMaterialRow
  const parsedRows: ParsedMaterialRow[] = body.items.map((item) => ({
    material_name: item['名称'] || '',
    specification: item['规格型号'] || '',
    quantity: parseFloat(item['数量'] || '0') || 0,
    unit: item['单位'] || '',
    technical_standard: item['技术标准'] || '',
    material_requirement: item['材质要求'] || '',
    technical_requirement: item['技术要求'] || '',
    applicable_conditions: item['适用条件'] || '',
    test_requirement: item['检验要求'] || '',
    acceptance_note: item['验收说明'] || '',
    warranty_period: item['质保期'] || '',
    deadline: item['交货期限'] || '',
    invoice_type: item['发票种类'] || '',
    brand: item['品牌'] || '',
    remarks: item['备注/附件'] || '',
    delivery_address: item['收货地址'] || '',
  }));

  return {
    items: parsedRows,
    summary: body.summary,
    markdownLength: body.markdownLength,
    elapsed: body.elapsed,
  };
}
