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 ?? `wp0-09-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseId = "TDD-WP0-PKG-001-portable-zip";
const caseDirectory = resolve(runDirectory, "cases", caseId);
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });

const commandSpecs = phase === "red"
  ? [["node --test tests/package/wp0-09-portable.test.mjs", ["node", "--test", "tests/package/wp0-09-portable.test.mjs"]]]
  : [
      ["pnpm test:security", ["pnpm", "test:security"]],
      ["pnpm test:package", ["pnpm", "test:package"]],
      ["pnpm validate:tdd-trace", ["pnpm", "validate:tdd-trace"]],
    ];
const environment = { ...process.env, DADA_EVIDENCE_DIR_PACKAGE: caseDirectory };
const startedAt = new Date().toISOString();
const commands = [];
for (const [command, invocation] of commandSpecs) {
  const started_at = new Date().toISOString();
  const [program, ...args] = invocation;
  const executable = process.platform === "win32" ? (process.env.ComSpec ?? "cmd.exe") : program;
  const actualArgs = process.platform === "win32" ? ["/d", "/s", "/c", [program, ...args].join(" ")] : args;
  const execution = spawnSync(executable, actualArgs, { encoding: "utf8", env: environment });
  if (execution.stdout) process.stdout.write(execution.stdout);
  if (execution.stderr) process.stderr.write(execution.stderr);
  commands.push({ command, exit_code: execution.status ?? 1, finished_at: new Date().toISOString(), started_at });
}

writeFileSync(resolve(caseDirectory, "commands.json"), `${JSON.stringify({ commands, phase, run_id: runId, schema_version: "1.0" }, null, 2)}\n`);
const evidenceRefs = ["package-manifest.json", "sha256.txt", "package-scan.json", "process-tree.json"];
const missingEvidence = phase === "green" ? evidenceRefs.filter((path) => !existsSync(resolve(caseDirectory, path))) : [];
const commandState = phase === "red" ? commands.every((item) => item.exit_code !== 0) : commands.every((item) => item.exit_code === 0);
const status = phase === "red" ? (commandState ? "red_confirmed" : "failed") : (commandState && missingEvidence.length === 0 ? "passed" : "failed");
const result = {
  acceptance_criteria: ["AC-24", "AC-41", "AC-56"],
  automation: ["automated"],
  commit: spawnSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).stdout.trim(),
  environment: { arch: process.arch, node: process.version.slice(1), os: process.platform },
  evidence_refs: evidenceRefs,
  finished_at: new Date().toISOString(),
  layer: ["PACKAGE_SECURITY"],
  manifest: { path: "tasks.manifest.json", sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase() },
  missing_evidence: missingEvidence,
  parent_family: "TDD-WP0-PKG-001",
  phase,
  release_gate: ["work_package:WP-0", "release:P0-A"],
  requirements: ["NFR-01", "NFR-09"],
  run_id: runId,
  schema_version: "1.0",
  started_at: startedAt,
  status,
  task_id: "TASK-WP0-09",
  test_id: caseId,
  work_package: "WP-0",
  worktree_under_test: spawnSync("git", ["status", "--porcelain"], { encoding: "utf8" }).stdout.trim() ? "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 !== (phase === "red" ? "red_confirmed" : "passed")) process.exit(1);
