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";
const manualReviewed = process.argv.includes("--manual-reviewed");
if (!["red", "green"].includes(phase)) throw new Error(`Unsupported phase: ${phase}`);
const runId = process.env.DADA_TDD_RUN_ID ?? `wp5-01-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP5-MAN-001-readonly-compiler");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });

const environment = { ...process.env, DADA_EVIDENCE_DIR_ASSET_COMPILER: caseDirectory };
const commands = phase === "red" ? [] : [
  ["unit", "pnpm test:unit"],
  ["security", "pnpm test:security"],
  ["package", "pnpm test:package"],
  ["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 });
}

if (phase === "red") {
  writeFileSync(resolve(caseDirectory, "red-observation.json"), `${JSON.stringify({
    expected_failure: "asset compiler entry and readonly conversion boundary are not implemented",
    observed_command: "pnpm vitest run tests/unit/wp5-01-asset-compiler.test.ts",
    observed_error: "Cannot find module packages/asset-compiler/src/index.js",
    status: "red_confirmed",
  }, null, 2)}\n`);
}

const automaticEvidence = ["compiler-report.json", "source-before.json", "source-after.json", "output-manifest.json"];
const missing = phase === "red" ? [] : automaticEvidence.filter((file) => !existsSync(resolve(caseDirectory, file)));
const commandState = phase === "red" || commandResults.every((result) => result.exit_code === 0);
const status = phase === "red"
  ? commandState && missing.length === 0 ? "red_confirmed" : "failed"
  : !commandState || missing.length > 0 ? "failed" : manualReviewed ? "passed" : "awaiting_manual_review";
const manualReview = manualReviewed
  ? { checks: ["source directories and source mtimes remain unchanged", "output manifest contains only declarative JSON and no source binary copies", "Lua/Prefab are represented only as non-executed conversion references"], reviewer: "user_confirmation", status: "passed" }
  : { checks: ["source directories and source mtimes remain unchanged", "output manifest contains only declarative JSON and no source binary copies", "Lua/Prefab are represented only as non-executed conversion references"], reviewer: "human_required", status: "pending" };
writeFileSync(resolve(caseDirectory, "manual-review.json"), `${JSON.stringify(manualReview, 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 evidenceRefs = [...automaticEvidence, "manual-review.json"];
writeFileSync(resolve(caseDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(caseDirectory, "result.json"), `${JSON.stringify({
  acceptance_criteria: ["AC-32", "AC-42"], automation: ["automated", "manual_review"], commit, evidence_refs: evidenceRefs,
  layer: ["UNIT", "PKG-SEC", "MANUAL"], manifest, missing_evidence: missing, phase, requirements: ["COL-01", "COL-02", "COL-03", "COL-04", "COL-05", "DYN-01", "DYN-02", "DYN-03", "DYN-04", "DYN-05", "DYN-06", "DYN-07", "DYN-08", "DYN-09", "STATIC-01", "STATIC-02", "STATIC-03", "STATIC-04", "TEXT-01", "TEXT-02", "TEXT-03", "TEXT-04", "TEXT-05", "TEXT-06", "TEXT-07", "TEXT-08", "TEXT-09", "TEXT-10", "TEXT-11", "TEXT-12", "TEXT-13", "TEXT-14"],
  run_id: runId, status, task_id: "TASK-WP5-01", test_id: "TDD-WP5-MAN-001-readonly-compiler", work_package: "WP-5",
  worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
}, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify({ cases: [{ missing_evidence: missing, status, test_id: "TDD-WP5-MAN-001-readonly-compiler" }], phase, run_id: runId, status }, null, 2)}\n`);
console.log(JSON.stringify({ cases: [{ missing_evidence: missing, status, test_id: "TDD-WP5-MAN-001-readonly-compiler" }], phase, run_id: runId, status }, null, 2));
if (status === "failed") process.exit(1);
