import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
import { assembleProblemUnits } from "../src/services/problemUnitAssembler";
import type { EvidenceItem } from "../src/types/stage1Contracts";

type ProbeCase = {
  case_id: string;
  route: string;
  expected_duplicate_collapses_min: number;
  input: {
    result_type?: "list" | "summary" | "object" | "chain" | "ranking";
    evidence: Array<Record<string, unknown>>;
    raw_entities?: Array<Record<string, unknown>>;
    summary?: Record<string, unknown>;
    risk_factors?: string[];
  };
};

describe("assistant stage2 duplicate collapse probe suite", () => {
  it("loads supplemental probe suite and confirms duplicate collapse signal", () => {
    const suitePath = path.resolve(process.cwd(), "../eval_cases/assistant_stage2_duplicate_probe_v0_1.json");
    const raw = fs.readFileSync(suitePath, "utf8");
    const suite = JSON.parse(raw.replace(/^\uFEFF/, "")) as {
      suite_id: string;
      suite_version: string;
      scenario_count: number;
      case_ids: string[];
      cases: ProbeCase[];
    };

    expect(suite.suite_id).toBe("assistant_stage2_duplicate_probe");
    expect(suite.suite_version).toBe("0.1.0");
    expect(Array.isArray(suite.case_ids)).toBe(true);
    expect(suite.scenario_count).toBe(suite.cases.length);

    for (const probeCase of suite.cases) {
      const assembled = assembleProblemUnits({
        route: probeCase.route,
        result_type: probeCase.input.result_type,
        evidence: probeCase.input.evidence as EvidenceItem[],
        raw_entities: probeCase.input.raw_entities,
        summary: probeCase.input.summary,
        risk_factors: probeCase.input.risk_factors,
        selection_reason: [],
        business_interpretation: []
      });

      expect(assembled.problem_unit_summary.duplicate_collapses).toBeGreaterThanOrEqual(
        probeCase.expected_duplicate_collapses_min
      );
      expect(assembled.problem_units.length).toBeGreaterThan(0);
      expect(assembled.candidate_evidence.length).toBeGreaterThan(0);
    }
  });
});
