import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, 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-02-${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_criteria: ["AC-27"], evidence: ["canvas-state.json", "db-diff.json", "trace.zip", "performance.json"], id: "TDD-WP4-CAN-001-fifty-elements", requirements: ["EDITOR-04", "EDITOR-05", "EDITOR-06", "EDITOR-07", "EDITOR-08", "EDITOR-09"] },
  { acceptance_criteria: ["AC-13", "AC-27"], evidence: ["canvas-state.json", "db-diff.json", "pixel-diff.json", "trace.zip"], id: "TDD-WP4-STK-001-transform-sticker", requirements: ["EDITOR-04", "EDITOR-05", "EDITOR-06", "EDITOR-07", "EDITOR-08", "EDITOR-09", "PROJECT-04"] },
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });

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

function findTraces(directory) {
  const traces = [];
  if (!existsSync(directory)) return traces;
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
    const path = resolve(directory, entry.name);
    if (entry.isDirectory()) traces.push(...findTraces(path));
    else if (entry.name === "trace.zip") traces.push(path);
  }
  return traces;
}
if (phase === "green") {
  const traces = findTraces(outputDirectory);
  const limitTrace = traces.find((path) => path.includes("fifty-first"));
  const stickerTrace = traces.find((path) => path.includes("ordinary-stickers"));
  if (limitTrace) copyFileSync(limitTrace, resolve(casesDirectory, cases[0].id, "trace.zip"));
  if (stickerTrace) copyFileSync(stickerTrace, resolve(casesDirectory, cases[1].id, "trace.zip"));
}

const commandState = phase === "red" ? true : 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;
if (phase === "red") {
  const observation = { expected_failure: "Canvas selection, 50-element limit, sticker transforms and editor controls were absent before TASK-WP4-02", observed_commands: ["pnpm vitest run tests/unit/wp4-02-editor-elements.test.ts"], observed_errors: ["Cannot find module '../../apps/web/src/editor-elements.js'"], status: "red_confirmed" };
  for (const item of cases) writeFileSync(resolve(casesDirectory, item.id, "red-observation.json"), `${JSON.stringify(observation, null, 2)}\n`);
}

const summaries = [];
for (const item of cases) {
  const directory = resolve(casesDirectory, item.id);
  const evidenceRefs = phase === "red" ? ["red-observation.json"] : item.evidence;
  const missingEvidence = evidenceRefs.filter((file) => !existsSync(resolve(directory, file)));
  const status = commandState && missingEvidence.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: item.acceptance_criteria, automation: ["automated"], commit, evidence_refs: evidenceRefs,
    layer: ["UNIT", "E2E", "VIS-PERF"], layer_notes: { PERFORMANCE: "current root runner reports not_applicable for TASK-WP0-01", VISUAL: "current root runner reports not_applicable for TASK-WP0-01" },
    manifest, missing_evidence: missingEvidence, phase, requirements: item.requirements, run_id: runId, status,
    task_id: "TASK-WP4-02", test_id: item.id, work_package: "WP-4", 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, "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 !== targetStatus) process.exit(1);
