import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";

type Stage3LifecycleProbeCase = {
  case_id: string;
  lifecycle_focus?: {
    domain?: string;
    targets?: string[];
  };
};

type Stage3LifecycleProbeSuite = {
  suite_id: string;
  suite_version: string;
  schema_version?: string;
  scenario_count: number;
  case_ids: string[];
  cases: Stage3LifecycleProbeCase[];
};

describe("assistant stage3 lifecycle prompt suite separation", () => {
  it("keeps stage2 canonical prompts as regression and stage3 prompts as separate lifecycle probe", () => {
    const stage2Path = path.resolve(process.cwd(), "../eval_cases/assistant_stage2_canonical_v0_1.json");
    const stage3Path = path.resolve(process.cwd(), "../eval_cases/assistant_stage3_lifecycle_probe_v0_1.json");

    const stage2 = JSON.parse(fs.readFileSync(stage2Path, "utf8").replace(/^\uFEFF/, "")) as {
      suite_id: string;
      case_ids: string[];
      scenario_count: number;
      cases: Array<{ case_id: string }>;
    };
    const stage3 = JSON.parse(fs.readFileSync(stage3Path, "utf8").replace(/^\uFEFF/, "")) as Stage3LifecycleProbeSuite;

    expect(stage2.suite_id).toBe("assistant_stage2_canonical");
    expect(stage2.case_ids).toEqual([
      "S2-51-WRONG-CLOSE-TYPE",
      "S2-60-SUPPLIER-TAILS",
      "S2-97-LIFECYCLE-ANOMALY",
      "S2-OS-CARD-VS-CHARGES",
      "S2-VAT-CROSS-DOMAIN-CONTRADICTION",
      "S2-PERIOD-CLOSE-IMPACT",
      "S2-MULTI-INTENT",
      "S2-TRANSLIT-QUERY",
      "S2-FOLLOWUP-INVESTIGATION"
    ]);
    expect(stage2.scenario_count).toBe(stage2.cases.length);

    expect(stage3.suite_id).toBe("assistant_stage3_lifecycle_probe");
    expect(stage3.suite_version).toBe("0.1.0");
    expect(stage3.scenario_count).toBe(stage3.cases.length);
    expect(stage3.case_ids.length).toBe(9);

    const domains = new Set(
      stage3.cases.map((item) => item.lifecycle_focus?.domain).filter((item): item is string => typeof item === "string" && item.length > 0)
    );
    expect(domains.has("51_60")).toBe(true);
    expect(domains.has("97")).toBe(true);
    expect(domains.has("fixed_asset")).toBe(true);
    expect(domains.has("vat_flow")).toBe(true);
    expect(domains.has("period_close")).toBe(true);

    const lifecycleTargets = new Set(
      stage3.cases.flatMap((item) => item.lifecycle_focus?.targets ?? []).filter((item) => typeof item === "string" && item.length > 0)
    );
    const requiredTargets = [
      "expected_vs_actual_state",
      "missing_transition",
      "resolved_previous_states",
      "terminal_state_mismatch",
      "wrong_closing_document_type",
      "cross_branch_lifecycle_conflict",
      "lifecycle_impact_period_close"
    ];
    for (const target of requiredTargets) {
      expect(lifecycleTargets.has(target), `missing lifecycle target: ${target}`).toBe(true);
    }
  });
});
