import { readFileSync } from "node:fs";

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

import { createApp } from "../../apps/api/src/app.js";
import { renderToolchainProbe } from "../../apps/web/src/toolchain-probe.js";
import { validateTddTrace } from "../../scripts/lib/tdd-trace.mjs";

function readManifest() {
  return JSON.parse(readFileSync(new URL("../../tasks.manifest.json", import.meta.url), "utf8"));
}

describe("TASK-WP0-01 minimum toolchain", () => {
  it("renders through React and Fabric at the frozen versions", () => {
    const probe = renderToolchainProbe();

    expect(probe.reactMarkup).toContain("Dada toolchain probe");
    expect(probe.fabricSvg).toContain("<rect");
    expect(probe.fabricVersion).toBe("7.4.0");
  });

  it("loads and closes Fastify with the frozen Swagger plugin", { timeout: 15_000 }, async () => {
    const app = await createApp();
    await app.ready();
    expect(app.hasPlugin("@fastify/swagger")).toBe(true);
    await app.close();
  });

  it("validates the frozen TDD trace", () => {
    const result = validateTddTrace();
    expect(result.errors).toEqual([]);
    expect(result.summary).toMatchObject({
      acceptanceCriteria: 52,
      parentFamilies: 89,
      requirements: 109,
      tasks: 52,
      testCases: 117,
      uiPages: 22,
    });
  });

  it("rejects a missing normative case", () => {
    const manifest = readManifest();
    manifest.case_catalog.pop();
    const result = validateTddTrace({ manifestOverride: manifest });
    expect(result.status).toBe("failed");
    expect(result.errors.some((error) => error.includes("normative case count"))).toBe(true);
  });

  it("rejects a duplicated case assignment", () => {
    const manifest = readManifest();
    manifest.tasks[1].case_ids.push(manifest.tasks[0].case_ids[0]);
    const result = validateTddTrace({ manifestOverride: manifest });
    expect(result.status).toBe("failed");
    expect(result.errors.some((error) => error.includes("duplicate case assignment"))).toBe(true);
  });
});
