import { readFile, rm } from "node:fs/promises";

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

import { parseCsvFile } from "../core/csv-parser.ts";
import {
  analyzeProductCombined,
  resolveLlmRuntimeConfig,
  resolveOnlineStandardizationModel,
} from "../standardization/standardization-llm.ts";
import { generateKeywordArtifacts } from "./keyword-artifact-generator.ts";

vi.mock("../core/csv-parser.ts", () => ({
  parseCsvFile: vi.fn(),
}));

vi.mock("../standardization/standardization-llm.ts", async (importOriginal) => {
  const actual = await importOriginal<typeof import("../standardization/standardization-llm.ts")>();
  return {
    ...actual,
    analyzeProductCombined: vi.fn(),
    resolveLlmRuntimeConfig: vi.fn(),
    resolveOnlineStandardizationModel: vi.fn(),
  };
});

const parseCsvFileMock = vi.mocked(parseCsvFile);
const analyzeProductCombinedMock = vi.mocked(analyzeProductCombined);
const resolveLlmRuntimeConfigMock = vi.mocked(resolveLlmRuntimeConfig);
const resolveOnlineStandardizationModelMock = vi.mocked(resolveOnlineStandardizationModel);
const originalEnv = { ...process.env };
const generatedDirs: string[] = [];

afterEach(async () => {
  vi.clearAllMocks();
  process.env = { ...originalEnv };
  await Promise.all(generatedDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});

describe("generateKeywordArtifacts", () => {
  it("records the standardization stage model in local keyword-process artifacts", async () => {
    process.env = {
      ...originalEnv,
      LLM_MODEL: "global-runtime-model",
      STANDARDIZATION_LLM_MODEL: "stage-standardization-model",
    };
    resolveLlmRuntimeConfigMock.mockResolvedValue({
      provider: "deepseek",
      baseURL: "https://api.deepseek.com",
      apiKey: "redacted",
      model: "stage-standardization-model",
    });
    resolveOnlineStandardizationModelMock.mockReturnValue("stage-standardization-model");
    parseCsvFileMock.mockReturnValue([{
      发票种类: "专票",
      名称: "不锈钢法兰",
      规格型号: "DN50 PN16",
      品牌: "沪工",
      数量: "10",
      单位: "个",
      "备注/附件": "304不锈钢",
      收货地址: "上海",
    }]);
    analyzeProductCombinedMock.mockResolvedValue({
      material: "304不锈钢",
      usage: "",
      simplified_spec: "DN50 PN16",
      brand_term: "沪工",
      keyword_parameter_terms: ["304不锈钢"],
      modifier_terms: [],
      alternative_terms: ["不锈钢法兰 DN50"],
      reasoning: "标准化阶段模型生成",
      suggested_keyword: "不锈钢法兰",
      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: [],
    });

    const result = await generateKeywordArtifacts({ row: 1, materialId: "material-1" });
    generatedDirs.push(result.runDir);
    const report = JSON.parse(await readFile(result.keywordProcessPath, "utf8")) as {
      llm_model?: string;
      llm_base_url?: string;
    };

    expect(report.llm_model).toBe("stage-standardization-model");
    expect(report.llm_base_url).toBe("https://api.deepseek.com");
    expect(report.llm_model).not.toBe("global-runtime-model");
  });
});
