import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

const phaseIndex = process.argv.indexOf("--phase");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
if (!["red", "green"].includes(phase)) throw new Error(`Unsupported phase: ${phase}`);
const runId = process.env.DADA_TDD_RUN_ID ?? `wp2-07-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const casesDirectory = resolve(runDirectory, "cases");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(casesDirectory, { recursive: true });

const cases = [
  { acceptance: ["AC-23", "AC-35"], evidence: ["download.json", "request.json", "response.json", "db-diff.json", "fs-before.json", "fs-after.json"], id: "TDD-WP2-EXP-001-same-blob-success", requirements: ["EXPORT-04"] },
  { acceptance: ["AC-35", "AC-55"], evidence: ["network-timeline.json", "response.json", "db-diff.json", "trace.zip", "screenshots/result.png"], id: "TDD-WP2-EXP-001-result-matrix", requirements: ["EXPORT-05", "EXPORT-06"] },
  { acceptance: ["AC-23", "AC-38"], evidence: ["response.json", "db-diff.json", "trace.zip", "screenshots/no-export.png"], id: "TDD-WP2-EXP-002-empty-latest", requirements: ["EXPORT-04"] },
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });

const commands = phase === "red"
  ? [
      ["unit", ["exec", "vitest", "run", "tests/unit/wp2-07-export-flow.test.ts"]],
      ["api", ["exec", "vitest", "run", "tests/api/wp2-07-latest-exports.test.ts"]],
      ["e2e", ["exec", "playwright", "test", "tests/e2e/project-latest-exports.spec.ts", "--config", "playwright.config.ts"]],
    ]
  : [["unit", ["test:unit"]], ["integration", ["test:integration"]], ["api", ["test:api"]], ["e2e", ["test:e2e"]], ["tdd-trace", ["validate:tdd-trace"]]];
const environment = { ...process.env, DADA_EVIDENCE_DIR_LATEST_EXPORTS: casesDirectory };
const commandResults = [];
for (const [name, args] of commands) {
  const command = `pnpm ${args.join(" ")}`;
  const started_at = new Date().toISOString();
  const result = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], { encoding: "utf8", env: environment });
  if (result.stdout) process.stdout.write(result.stdout);
  if (result.stderr) process.stderr.write(result.stderr);
  commandResults.push({ command, exit_code: result.status ?? 1, finished_at: new Date().toISOString(), name, started_at });
}
if (phase === "green") {
  const traces = [];
  const visit = (directory) => {
    if (!existsSync(directory)) return;
    for (const entry of readdirSync(directory, { withFileTypes: true })) {
      const path = resolve(directory, entry.name);
      if (entry.isDirectory()) visit(path);
      else if (entry.name === "trace.zip" && path.includes("project-latest-exports")) traces.push(path);
    }
  };
  visit(resolve("test-results", "e2e"));
  traces.sort((left, right) => statSync(left).mtimeMs - statSync(right).mtimeMs);
  const emptyTrace = traces.find((path) => path.includes("two-allowed-actions"));
  const matrixTrace = traces.find((path) => path.includes("download-and-persistence"));
  if (emptyTrace) copyFileSync(emptyTrace, resolve(casesDirectory, "TDD-WP2-EXP-002-empty-latest", "trace.zip"));
  if (matrixTrace) copyFileSync(matrixTrace, resolve(casesDirectory, "TDD-WP2-EXP-001-result-matrix", "trace.zip"));
}
const commandState = phase === "red" ? commandResults.every((result) => result.exit_code !== 0) : commandResults.every((result) => result.exit_code === 0);
const manifest = { path: "tasks.manifest.json", sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase() };
const commit = spawnSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).stdout.trim();
const dirty = spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }).stdout.trim().length > 0;
const summaries = [];
for (const item of cases) {
  const directory = resolve(casesDirectory, item.id);
  writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
  if (phase === "red") writeFileSync(resolve(directory, "red-observation.json"), `${JSON.stringify({ expected_failure: "Latest export persistence, private downloads, result matrix, and no-export UI are absent", status: commandState ? "red_confirmed" : "failed" }, null, 2)}\n`);
  const evidenceRefs = phase === "red" ? ["red-observation.json"] : item.evidence;
  const missingEvidence = evidenceRefs.filter((file) => !existsSync(resolve(directory, file)));
  const targetStatus = phase === "red" ? "red_confirmed" : "passed";
  const status = commandState && missingEvidence.length === 0 ? targetStatus : "failed";
  writeFileSync(resolve(directory, "result.json"), `${JSON.stringify({
    acceptance_criteria: item.acceptance, automation: ["automated"], commit, evidence_refs: evidenceRefs,
    layer: ["DB", "API", "UNIT", "E2E"], manifest, missing_evidence: missingEvidence, phase,
    requirements: item.requirements, run_id: runId, status, task_id: "TASK-WP2-07", test_id: item.id,
    work_package: "WP-2", worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
  }, null, 2)}\n`);
  summaries.push({ missing_evidence: missingEvidence, status, test_id: item.id });
}
const targetStatus = phase === "red" ? "red_confirmed" : "passed";
const status = summaries.every((item) => item.status === targetStatus) ? targetStatus : "failed";
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify({ cases: summaries, phase, run_id: runId, status }, null, 2)}\n`);
console.log(JSON.stringify({ cases: summaries, phase, run_id: runId, status }, null, 2));
if (status !== targetStatus) process.exit(1);
