import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync, readFileSync } 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 ?? `wp3-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: ["AC-30", "AC-51"], evidence: ["response.json", "db-diff.json", "screenshots/model-states.png"], id: "TDD-WP3-MDL-003-runtime-recommendation", requirements: ["ADMIN-03", "GEN-15"] },
  { acceptance: ["AC-51"], evidence: ["response.json", "db-diff.json", "external-calls.json", "screenshots/recovery.png"], id: "TDD-WP3-BAL-001-confirmed-recovery", requirements: ["ADMIN-09", "GEN-14", "GEN-15"] },
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });

const commands = phase === "red"
  ? [["unit-red", ["exec", "vitest", "run", "tests/unit/wp3-02-runtime-recommendation.test.ts"]], ["integration-red", ["exec", "vitest", "run", "tests/integration/wp3-02-runtime-recovery.test.ts"]]]
  : [
      ["integration", ["test:integration"]],
      ["worker", ["test:worker"]],
      ["e2e", ["test:e2e"]],
      ["unit", ["test:unit"]],
      ["api", ["test:api"]],
      ["tdd-trace", ["validate:tdd-trace"]],
    ];
const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_RUNTIME: casesDirectory,
  DADA_PLAYWRIGHT_OUTPUT_DIR: resolve("test-results", runId, "e2e"),
};
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 });
}

const commandState = phase === "red" ? commandResults.every((result) => result.exit_code !== 0) : 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;
const summaries = [];
for (const item of cases) {
  const directory = resolve(casesDirectory, item.id);
  writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
  const evidenceRefs = phase === "red" ? ["red-observation.json"] : item.evidence;
  if (phase === "red") writeFileSync(resolve(directory, "red-observation.json"), `${JSON.stringify({
    expected_failure: "TASK-WP3-02 had no runtime recommendation derivation and WP2-06 worker runtime used an incompatible schema",
    observed_commands: ["pnpm vitest run tests/unit/wp3-02-runtime-recommendation.test.ts", "pnpm vitest run tests/integration/wp3-02-runtime-recovery.test.ts"],
    observed_errors: ["recommended_model_id was null", "SqliteError: table model_runtime_availability has no column named gateway_account_ref"],
    status: "red_confirmed",
  }, null, 2)}\n`);
  const missingEvidence = evidenceRefs.filter((file) => !existsSync(resolve(directory, file)));
  const targetStatus = phase === "red" ? "red_confirmed" : "passed";
  const status = commandState && missingEvidence.length === 0 ? targetStatus : "failed";
  writeFileSync(resolve(directory, "result.json"), `${JSON.stringify({
    acceptance_criteria: item.acceptance, automation: ["automated"], commit, evidence_refs: evidenceRefs,
    manifest, missing_evidence: missingEvidence, phase, requirements: item.requirements,
    run_id: runId, status, task_id: "TASK-WP3-02", test_id: item.id, work_package: "WP-3",
    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, "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);
