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 ?? `wp1-05-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const deleteCase = "TDD-WP1-DEL-001-account-delete";
const retentionCase = "TDD-WP1-DEL-002-anonymous-retention";
const directories = {
  [deleteCase]: resolve(runDirectory, "cases", deleteCase),
  [retentionCase]: resolve(runDirectory, "cases", retentionCase),
};
const playwrightDirectory = resolve(runDirectory, "playwright");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
for (const directory of Object.values(directories)) mkdirSync(directory, { recursive: true });

const commandsToRun = phase === "red"
  ? [
      ["delete-integration", ["exec", "vitest", "run", "tests/integration/wp1-05-account-deletion.test.ts"]],
      ["retention-worker", ["exec", "vitest", "run", "tests/worker/wp1-05-retention-cleanup.test.ts"]],
      ["delete-api", ["exec", "vitest", "run", "tests/api/wp1-05-account-deletion.test.ts"]],
      ["settings-e2e", ["exec", "playwright", "test", "tests/e2e/account-settings.spec.ts", "--config", "playwright.config.ts"]],
    ]
  : [
      ["integration", ["test:integration"]],
      ["api", ["test:api"]],
      ["worker", ["test:worker"]],
      ["e2e", ["test:e2e"]],
      ["security", ["test:security"]],
      ["package", ["test:package"]],
      ["tdd-trace", ["validate:tdd-trace"]],
    ];
const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_DELETE: directories[deleteCase],
  DADA_EVIDENCE_DIR_RETENTION: directories[retentionCase],
  DADA_PLAYWRIGHT_OUTPUT_DIR: playwrightDirectory,
};
const commandResults = [];
for (const [name, args] of commandsToRun) {
  const command = `pnpm ${args.join(" ")}`;
  const started_at = new Date().toISOString();
  const execution = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], { encoding: "utf8", env: environment });
  if (execution.stdout) process.stdout.write(execution.stdout);
  if (execution.stderr) process.stderr.write(execution.stderr);
  commandResults.push({ command, exit_code: execution.status ?? 1, finished_at: new Date().toISOString(), name, started_at });
}

function find(root, name) {
  if (!existsSync(root)) return [];
  return readdirSync(root).flatMap((entry) => {
    const child = resolve(root, entry);
    return statSync(child).isDirectory() ? find(child, name) : entry === name ? [child] : [];
  });
}
if (phase === "green") {
  const trace = find(playwrightDirectory, "trace.zip").find((path) => path.replaceAll("\\", "/").includes("account-settings"));
  if (trace) copyFileSync(trace, resolve(directories[deleteCase], "trace.zip"));
}
for (const directory of Object.values(directories)) {
  writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
}
const expectedEvidence = phase === "red"
  ? { [deleteCase]: ["red-observation.json"], [retentionCase]: ["red-observation.json"] }
  : {
      [deleteCase]: ["response.json", "db-diff.json", "worker-events.json", "trace.zip"],
      [retentionCase]: ["db-diff.json", "retention-events.json", "redaction.json"],
    };
const commandState = phase === "red"
  ? commandResults.every((result) => result.exit_code !== 0)
  : commandResults.every((result) => result.exit_code === 0);
if (phase === "red") {
  for (const [testId, directory] of Object.entries(directories)) {
    writeFileSync(resolve(directory, "red-observation.json"), `${JSON.stringify({
      expected_failure: testId === deleteCase ? "account deletion transaction and settings flow are absent" : "anonymous retention cleanup is absent",
      status: commandState ? "red_confirmed" : "failed",
    }, null, 2)}\n`);
  }
}
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 results = Object.entries(directories).map(([testId, directory]) => {
  const evidence_refs = expectedEvidence[testId];
  const missing_evidence = evidence_refs.filter((file) => !existsSync(resolve(directory, file)));
  const status = commandState && missing_evidence.length === 0 ? (phase === "red" ? "red_confirmed" : "passed") : "failed";
  const result = {
    acceptance_criteria: ["AC-22", "AC-39", "AC-56"], automation: ["automated"], commit,
    evidence_refs, layer: testId === deleteCase ? ["DB", "API", "WRK", "E2E"] : ["DB", "WRK"],
    manifest, missing_evidence, phase, requirements: ["AUTH-06"], run_id: runId, status,
    task_id: "TASK-WP1-05", test_id: testId, work_package: "WP-1",
    worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
  };
  writeFileSync(resolve(directory, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
  return result;
});
const targetStatus = phase === "red" ? "red_confirmed" : "passed";
const passed = results.every((result) => result.status === targetStatus);
const summary = { cases: results.map(({ missing_evidence, status, test_id }) => ({ missing_evidence, status, test_id })), phase, run_id: runId, status: passed ? targetStatus : "failed" };
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify(summary, null, 2)}\n`);
console.log(JSON.stringify(summary, null, 2));
if (!passed) process.exit(1);
