import fs from "fs";
import os from "os";
import path from "path";
import { afterEach, describe, expect, it } from "vitest";
import {
  findMatchingKnownFailureEntries,
  normalizeKnownFailuresDocument,
  renderKnownFailuresMarkdown,
  validateKnownFailuresDocument,
} from "./index.mjs";

const tempDirs = [];

afterEach(() => {
  for (const tempDir of tempDirs.splice(0)) {
    fs.rmSync(tempDir, { recursive: true, force: true });
  }
});

describe("known failures core", () => {
  it("matches entries by service, type, path, and failure key", () => {
    const document = normalizeKnownFailuresDocument({
      schemaVersion: 1,
      entries: [
        {
          id: "bad-message",
          title: "Bad message bug",
          classification: "product_bug",
          state: "open",
          issue: {
            repo: "acme/repo",
            number: 12,
            url: "https://github.com/acme/repo/issues/12",
          },
          description: "Wrong message",
          whyFailing: "Payload is wrong",
          lastReviewedAt: "2026-04-27",
          matches: [
            {
              service: "api",
              type: "int",
              path: "src/api/routes/__testkit__/failing.int.testkit.ts",
              failureKey: "returns the wrong message",
            },
          ],
        },
      ],
    });

    const matches = findMatchingKnownFailureEntries(document, {
      service: "api",
      type: "int",
      path: "src/api/routes/__testkit__/failing.int.testkit.ts",
      error: "boom",
      failureDetails: [{ key: "returns the wrong message" }],
    });

    expect(matches).toHaveLength(1);
    expect(matches[0].id).toBe("bad-message");
  });

  it("validates status coverage and filesystem matches", () => {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "testkit-known-failures-"));
    tempDirs.push(tempDir);
    const testPath = path.join(tempDir, "src/api/routes/__testkit__/failing.int.testkit.ts");
    fs.mkdirSync(path.dirname(testPath), { recursive: true });
    fs.writeFileSync(testPath, "export default {};\n");

    const document = normalizeKnownFailuresDocument({
      schemaVersion: 1,
      issueRepo: "acme/repo",
      entries: [
        {
          id: "bad-message",
          title: "Bad message bug",
          classification: "product_bug",
          state: "open",
          issue: {
            repo: "acme/repo",
            number: 12,
            url: "https://github.com/acme/repo/issues/12",
          },
          description: "Wrong message",
          whyFailing: "Payload is wrong",
          lastReviewedAt: "2026-04-27",
          matches: [
            {
              service: "api",
              type: "int",
              path: "src/api/routes/__testkit__/failing.int.testkit.ts",
            },
          ],
        },
      ],
    });

    const result = validateKnownFailuresDocument(document, {
      productDir: tempDir,
      statusArtifact: {
        tests: [
          {
            service: "api",
            type: "int",
            path: "src/api/routes/__testkit__/failing.int.testkit.ts",
            status: "failed",
          },
          {
            service: "api",
            type: "int",
            path: "src/api/routes/__testkit__/other.int.testkit.ts",
            status: "failed",
          },
        ],
      },
    });

    expect(result.errors).toEqual([]);
    expect(result.stats.failedTests).toBe(2);
    expect(result.stats.triagedFailedTests).toBe(1);
    expect(result.warnings).toContain(
      "Untriaged failed test: src/api/routes/__testkit__/other.int.testkit.ts"
    );
  });

  it("renders markdown from the canonical document", () => {
    const markdown = renderKnownFailuresMarkdown(
      normalizeKnownFailuresDocument({
        schemaVersion: 1,
        entries: [
          {
            id: "bad-message",
            title: "Bad message bug",
            classification: "product_bug",
            state: "open",
            issue: {
              repo: "acme/repo",
              number: 12,
              url: "https://github.com/acme/repo/issues/12",
            },
            description: "Wrong message",
            whyFailing: "Payload is wrong",
            lastReviewedAt: "2026-04-27",
            matches: [{ path: "src/api/routes/__testkit__/failing.int.testkit.ts" }],
          },
        ],
      })
    );

    expect(markdown).toContain("# Bourne Bugs");
    expect(markdown).toContain("[#12](https://github.com/acme/repo/issues/12)");
  });
});
