import assert from "node:assert/strict";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";

import { auditCaseRunSources, renderCaseRunAuditText } from "../src/hwlab-caserun-audit.ts";

test("CaseRun static audit passes clean source modules", async () => {
  const root = await mkdtemp(path.join(os.tmpdir(), "caserun-audit-clean-"));
  const sourceDir = path.join(root, "tools", "src");
  await mkdir(sourceDir, { recursive: true });
  await writeFile(path.join(sourceDir, "hwlab-caserun-clean.ts"), "export const value: string = 'ok';\n", "utf8");

  const report = await auditCaseRunSources({ root });
  assert.equal(report.ok, true, renderCaseRunAuditText(report));
  assert.equal(report.status, "passed");
  assert.equal(report.findingCount, 0);
});

test("CaseRun static audit returns typed findings for representative source defects", async () => {
  const root = await mkdtemp(path.join(os.tmpdir(), "caserun-audit-"));
  const sourceDir = path.join(root, "tools", "src");
  await mkdir(sourceDir, { recursive: true });
  await writeFile(path.join(sourceDir, "hwlab-caserun-runtime.ts"), [
    "import { helper } from './hwlab-caserun-helper.ts';",
    "const first = 1; const second = 2;",
    "export type MissingAlias = MissingCaseRunType;",
    "export const incompatibleValue: string = first;",
    "export const missingProperty = ({ value: first }).missing;",
    "export const runtimeValue = helper(first + second);",
  ].join("\n"), "utf8");
  await writeFile(path.join(sourceDir, "hwlab-caserun-helper.ts"), [
    "import { runtimeValue } from './hwlab-caserun-runtime.ts';",
    "function duplicate(value: string) { return String(value).trim(); }",
    "export function helper(value: number) { return duplicate(runtimeValue + value); }",
  ].join("\n"), "utf8");
  await writeFile(path.join(sourceDir, "hwlab-caserun-other.ts"), [
    "function duplicate(value: string) { return String(value).trim(); }",
    ...Array.from({ length: 20 }, (_, index) => `export const line${index} = ${index};`),
  ].join("\n"), "utf8");

  const report = await auditCaseRunSources({ root, maxLines: 10 });
  const codes = new Set(report.findings.map((finding) => finding.code));
  assert.equal(report.ok, false);
  assert.equal(report.status, "failed");
  assert.ok(codes.has("caserun_type_ts2304"));
  assert.ok(codes.has("caserun_type_ts2322"));
  assert.ok(codes.has("caserun_type_ts2339"));
  assert.ok(codes.has("caserun_runtime_reverse_dependency"));
  assert.ok(codes.has("caserun_dependency_cycle"));
  assert.ok(codes.has("caserun_duplicate_pure_helper"));
  assert.ok(codes.has("caserun_compressed_top_level_declaration"));
  assert.ok(codes.has("caserun_source_line_limit_exceeded"));
});
