import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, 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 ?? `wp4-05-${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 combinations = ["3x4", "1x1", "4x3", "9x16"].flatMap((ratio) => ["jpg80", "jpg92", "jpg100", "png"].flatMap((format) => ["result.json", "image-metadata.json", "pixel-diff.json", "export-hash.json"].map((file) => `combinations/${ratio}-${format}/${file}`)));
const cases = [
  { id: "TDD-WP4-EXP-001-cancel-pending-edit", evidence: ["network-timeline.json", "db-diff.json", "trace.zip"] },
  { id: "TDD-WP4-EXP-001-confirm-pending-edit", evidence: ["undo-trace.json", "network-timeline.json", "export-hash.json", "trace.zip", "screenshots/pending-confirm.png"] },
  { id: "TDD-WP4-EXP-001-format-ratio", evidence: [...combinations, "performance.json"] },
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });

const outputDirectory = resolve(runDirectory, "playwright-output");
const environment = { ...process.env, DADA_EVIDENCE_DIR_EXPORT: casesDirectory, DADA_PLAYWRIGHT_OUTPUT_DIR: outputDirectory };
const commands = phase === "red" ? [] : [
  ["unit", "pnpm test:unit"],
  ["e2e", "pnpm test:e2e"],
  ["visual", "pnpm test:visual"],
  ["performance", "pnpm test:performance"],
  ["tdd-trace", "pnpm validate:tdd-trace"],
];
const commandResults = [];
for (const [name, command] of commands) {
  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 });
}

function traces(directory) {
  if (!existsSync(directory)) return [];
  return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
    const path = resolve(directory, entry.name);
    return entry.isDirectory() ? traces(path) : entry.name === "trace.zip" ? [path] : [];
  });
}
if (phase === "green") {
  const found = traces(outputDirectory);
  const needles = ["outside-history-and-export", "saves-the-same-bytes"];
  needles.forEach((needle, index) => {
    const trace = found.find((path) => path.includes(needle));
    if (trace) copyFileSync(trace, resolve(casesDirectory, cases[index].id, "trace.zip"));
  });
} else {
  const observation = {
    expected_failure: "TASK-WP4-05 export compositor and enabled editor export entry did not exist",
    observed_command: "pnpm vitest run tests/unit/wp4-05-export-compositor.test.ts",
    observed_error: "Cannot find module ../../apps/web/src/export-compositor.js",
    status: "red_confirmed",
  };
  for (const item of cases) writeFileSync(resolve(casesDirectory, item.id, "red-observation.json"), `${JSON.stringify(observation, null, 2)}\n`);
}

const commandState = phase === "red" || 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 = cases.map((item) => {
  const directory = resolve(casesDirectory, item.id);
  const refs = phase === "red" ? ["red-observation.json"] : item.evidence;
  const missing = refs.filter((file) => !existsSync(resolve(directory, file)));
  const status = commandState && missing.length === 0 ? phase === "red" ? "red_confirmed" : "passed" : "failed";
  writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
  writeFileSync(resolve(directory, "result.json"), `${JSON.stringify({
    acceptance_criteria: ["AC-23"], automation: ["automated"], commit, evidence_refs: refs,
    layer: ["UNIT", "E2E", "VIS-PERF"], manifest, missing_evidence: missing, phase,
    requirements: ["EXPORT-01", "EXPORT-02", "EXPORT-03", "PROJECT-04", "PROJECT-06"], run_id: runId,
    status, task_id: "TASK-WP4-05", test_id: item.id, work_package: "WP-4",
    worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
  }, null, 2)}\n`);
  return { missing_evidence: missing, status, test_id: item.id };
});
const status = summaries.every((item) => item.status === (phase === "red" ? "red_confirmed" : "passed")) ? phase === "red" ? "red_confirmed" : "passed" : "failed";
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
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 === "failed") process.exit(1);
