import { describe, expect, it } from "vitest";

import type { RawCsvRow } from "../core/types.ts";
import {
  formatParameterInterpretationsSummary,
  parseOfflineCombinedResult,
} from "./offline-batch-result.ts";
import {
  buildCategorizedHumanFixHint,
  normalizeHumanFixHint,
} from "./human-fix-hint.ts";

const baseRawRow: RawCsvRow = {
  发票种类: "",
  名称: "劳保手套",
  规格型号: "",
  品牌: "",
  数量: "5",
  单位: "打",
  "备注/附件": "维修保养",
  收货地址: "",
};

describe("human fix hint formatter", () => {
  it("groups related missing fields into categorized bullet sections", () => {
    const hint = buildCategorizedHumanFixHint(["材质", "尺码", "防护性能", "品牌", "质保期"]);

    expect(hint).toContain("【材质/成分】");
    expect(hint).toContain("【规格/尺寸】");
    expect(hint).toContain("【功能/性能】");
    expect(hint).toContain("\n- ");
    expect(hint).not.toContain("品牌");
    expect(hint).not.toContain("质保期");
  });

  it("falls back to comprehensive default categories when missing fields are empty", () => {
    const hint = buildCategorizedHumanFixHint([]);

    expect(hint).toContain("【材质/成分】");
    expect(hint).toContain("【规格/尺寸】");
    expect(hint).toContain("【型号/等级】");
    expect(hint).toContain("【电气/动力参数】");
    expect(hint).toContain("【结构/接口/安装方式】");
    expect(hint).toContain("【适配对象/使用场景】");
    expect(hint).toContain("【数量/包装/计量信息】");
  });

  it("keeps structured hints and upgrades legacy one-line hints", () => {
    const structuredHint = [
      "请补充以下关键信息，便于准确识别采购对象并完成询价：",
      "【材质/成分】",
      "- 请明确主体材质。",
    ].join("\n");

    expect(normalizeHumanFixHint(structuredHint, ["材质"])).toBe(structuredHint);

    const normalizedLegacyHint = normalizeHumanFixHint("请补充：材质、规格", ["材质", "规格"]);
    expect(normalizedLegacyHint).toContain("【材质/成分】");
    expect(normalizedLegacyHint).toContain("【规格/尺寸】");
    expect(normalizedLegacyHint).not.toContain("【补充说明】");
  });
});

describe("offline combined result human_fix_hint", () => {
  it("normalizes failed one-line hints into categorized sections", () => {
    const result = parseOfflineCombinedResult(JSON.stringify({
      material: "",
      usage: "",
      simplified_spec: "",
      brand_term: "",
      keyword_parameter_terms: [],
      modifier_terms: [],
      alternative_terms: [],
      reasoning: "",
      suggested_keyword: "",
      product_type: "",
      structure_summary: "",
      component_roles: "",
      purchase_type: "",
      outcome: "failed",
      can_search_1688: false,
      missing_required_fields: ["材质", "功能要求"],
      failure_reason: "",
      human_fix_hint: "请补充：材质、功能要求",
      required_attributes_summary: "",
      identified_unique_model: "",
    }), baseRawRow);

    expect(result.human_fix_hint).toContain("【材质/成分】");
    expect(result.human_fix_hint).toContain("【功能/性能】");
    expect(result.human_fix_hint).not.toContain("【补充说明】");
  });

  it("uses comprehensive structured fallback when failed result has no hint", () => {
    const result = parseOfflineCombinedResult(JSON.stringify({
      material: "",
      usage: "",
      simplified_spec: "",
      brand_term: "",
      keyword_parameter_terms: [],
      modifier_terms: [],
      alternative_terms: [],
      reasoning: "",
      suggested_keyword: "",
      product_type: "",
      structure_summary: "",
      component_roles: "",
      purchase_type: "",
      outcome: "failed",
      can_search_1688: false,
      missing_required_fields: [],
      failure_reason: "",
      human_fix_hint: "",
      required_attributes_summary: "",
      identified_unique_model: "",
    }), baseRawRow);

    expect(result.human_fix_hint).toContain("【材质/成分】");
    expect(result.human_fix_hint).toContain("【功能/性能】");
    expect(result.human_fix_hint).toContain("【适配对象/使用场景】");
  });
});

describe("offline combined result parameter interpretations", () => {
  it("parses parameter interpretations and builds an AI reasoning summary section", () => {
    const result = parseOfflineCombinedResult(JSON.stringify({
      material: "丁基橡胶",
      usage: "防水密封",
      simplified_spec: "2R",
      brand_term: "",
      keyword_parameter_terms: ["2R"],
      modifier_terms: [],
      alternative_terms: ["丁基防水胶带"],
      reasoning: "原始需求为 2R 丁基防水胶带。",
      suggested_keyword: "2R丁基防水胶带",
      product_type: "独立材料",
      structure_summary: "丁基胶带类防水材料",
      component_roles: "防水密封材料",
      purchase_type: "可直接购买",
      outcome: "success",
      can_search_1688: true,
      missing_required_fields: [],
      failure_reason: "",
      human_fix_hint: "",
      required_attributes_summary: "具备材质和型号参数",
      parameter_interpretations: [
        {
          term: "2R",
          term_type: "parameter",
          product_context: "丁基防水胶带",
          interpretation: "双面防水/双面胶接类参数",
          evidence: "防水胶带采购语境",
        },
        {
          term: "  ",
          term_type: "parameter",
          product_context: "丁基防水胶带",
          interpretation: "无效术语会被忽略",
          evidence: "",
        },
      ],
      identified_unique_model: "",
    }), {
      ...baseRawRow,
      名称: "丁基防水胶带",
      规格型号: "2R",
    });

    expect(result.parameter_interpretations).toEqual([
      {
        term: "2R",
        term_type: "parameter",
        product_context: "丁基防水胶带",
        interpretation: "双面防水/双面胶接类参数",
        evidence: "防水胶带采购语境",
      },
    ]);
    expect(formatParameterInterpretationsSummary(result.parameter_interpretations)).toContain("参数解读：2R（丁基防水胶带）：双面防水/双面胶接类参数");
  });
});
