import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, 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 ?? `wp2-03-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseId = "TDD-WP2-PROJ-003-trash-restore-purge";
const caseDirectory = resolve(runDirectory, "cases", caseId);
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });

const commands = phase === "red"
  ? [
      ["integration", ["exec", "vitest", "run", "tests/integration/wp2-03-project-lifecycle.test.ts"]],
      ["api", ["exec", "vitest", "run", "tests/api/wp2-03-project-lifecycle.test.ts"]],
      ["worker", ["exec", "vitest", "run", "tests/worker/wp2-03-project-cleanup.test.ts"]],
      ["e2e", ["exec", "playwright", "test", "tests/e2e/project-trash.spec.ts", "--config", "playwright.config.ts"]],
    ]
  : [
      ["integration", ["test:integration"]], ["api", ["test:api"]],
      ["worker", ["test:worker"]], ["e2e", ["test:e2e"]], ["tdd-trace", ["validate:tdd-trace"]],
    ];
const environment = { ...process.env, DADA_EVIDENCE_DIR_PROJECT_TRASH: caseDirectory };
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 });
}
writeFileSync(resolve(caseDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
const commandState = phase === "red"
  ? commandResults.every((result) => result.exit_code !== 0)
  : commandResults.every((result) => result.exit_code === 0);
if (phase === "red") {
  writeFileSync(resolve(caseDirectory, "red-observation.json"), `${JSON.stringify({
    expected_failure: "Project lifecycle routes, exact restore boundary, purge queue, worker cleanup and trash UI are absent",
    status: commandState ? "red_confirmed" : "failed",
  }, null, 2)}\n`);
}
const evidenceRefs = phase === "red" ? ["red-observation.json"] : ["response.json", "db-diff.json", "worker-events.json"];
const missingEvidence = evidenceRefs.filter((file) => !existsSync(resolve(caseDirectory, file)));
const targetStatus = phase === "red" ? "red_confirmed" : "passed";
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 status = commandState && missingEvidence.length === 0 ? targetStatus : "failed";
const result = {
  acceptance_criteria: ["AC-21"], automation: ["automated"], commit,
  evidence_refs: evidenceRefs, layer: ["DB", "API", "WRK", "E2E"], manifest, missing_evidence: missingEvidence,
  phase, requirements: ["PROJECT-03", "PROJECT-08"], run_id: runId, status,
  task_id: "TASK-WP2-03", test_id: caseId, work_package: "WP-2",
  worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
};
writeFileSync(resolve(caseDirectory, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
const summary = { cases: [{ missing_evidence: missingEvidence, status, test_id: caseId }], phase, run_id: runId, status };
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify(summary, null, 2)}\n`);
console.log(JSON.stringify(summary, null, 2));
if (status !== targetStatus) process.exit(1);
