import type {
  RawCsvRow,
  StandardizationSourceSnapshot,
} from "../core/types.ts";

function buildLine(label: string, value: unknown) {
  const text = String(value ?? "").trim();
  return text ? `${label}：${text}` : "";
}

export const COMBINED_STANDARDIZATION_PROMPT_KEY = "automation.standardization.combined.system";

export function buildCombinedStandardizationUserMessageFromRaw(row: RawCsvRow): string {
  return [
    buildLine("名称", row.名称),
    buildLine("规格型号", row.规格型号),
    buildLine("品牌", row.品牌),
    buildLine("数量", `${row.数量} ${row.单位}`.trim()),
    buildLine("备注/附件", row["备注/附件"]),
    buildLine("技术标准", row.技术标准),
    buildLine("材质要求", row.材质要求),
    buildLine("技术要求", row.技术要求),
    buildLine("适用条件", row.适用条件),
    buildLine("检验要求", row.检验要求),
    buildLine("验收说明", row.验收说明),
    buildLine("质保期", row.质保期),
    buildLine("交货期限", row.交货期限),
    buildLine("发票种类", row.发票种类),
    buildLine("收货地址", row.收货地址),
    buildLine("来源文件", row.来源文件),
  ].filter(Boolean).join("\n");
}

export function buildCombinedStandardizationUserMessageFromSource(source: StandardizationSourceSnapshot): string {
  return [
    buildLine("名称", source.material_name),
    buildLine("规格型号", source.specification),
    buildLine("品牌", source.brand),
    buildLine("数量", `${source.quantity ?? ""} ${source.unit}`.trim()),
    buildLine("备注/附件", source.remarks),
    buildLine("技术标准", source.technical_standard),
    buildLine("材质要求", source.material_requirement),
    buildLine("技术要求", source.technical_requirement),
    buildLine("适用条件", source.applicable_conditions),
    buildLine("检验要求", source.test_requirement),
    buildLine("验收说明", source.acceptance_note),
    buildLine("质保期", source.warranty_period),
    buildLine("交货期限", source.deadline),
    buildLine("发票种类", source.invoice_type),
    buildLine("收货地址", source.delivery_address),
    buildLine("来源文件", source.source_file),
  ].filter(Boolean).join("\n");
}

export function buildCombinedStandardizationBatchUserMessage(
  rows: Array<{ materialId: string; row: RawCsvRow }>,
): string {
  const rowBlocks = rows.map(({ materialId, row }, index) => [
    `## 物料 ${index + 1}`,
    `material_id：${materialId}`,
    buildCombinedStandardizationUserMessageFromRaw(row),
  ].filter(Boolean).join("\n"));

  return [
    `请对下面 ${rows.length} 条物料逐条完成标准化分析。`,
    "只返回一个合法 JSON 对象，不要 Markdown，不要解释。",
    "返回格式必须是：{\"items\":[{\"material_id\":\"原 material_id\", ...单条标准化字段}]}。",
    "items 数量必须和输入物料数量一致；每个 item 必须原样带回对应的 material_id。",
    "每个 item 中除 material_id 外，其余字段沿用单条标准化的 JSON 字段约定。",
    "",
    rowBlocks.join("\n\n"),
  ].join("\n");
}
