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 runId = process.env.DADA_TDD_RUN_ID ?? `wp0-01-green-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const caseId = "TDD-WP0-DEP-001-frozen-toolchain";
const evidenceDirectory = resolve("artifacts", "tdd", runId, "cases", caseId);

if (existsSync(evidenceDirectory)) {
  throw new Error(`Evidence run already exists: ${runId}`);
}
mkdirSync(evidenceDirectory, { recursive: true });

const commandDefinitions = [
  { command: "pnpm install --frozen-lockfile --offline", args: ["install", "--frozen-lockfile", "--offline"] },
  { command: "pnpm test:unit", args: ["test:unit"] },
  { command: "pnpm test:security", args: ["test:security"] },
  { command: "pnpm test:package", args: ["test:package"] },
  { command: "pnpm validate:tdd-trace", args: ["validate:tdd-trace"] },
];

const startedAt = new Date().toISOString();
const commands = [];
for (const definition of commandDefinitions) {
  const commandStartedAt = new Date().toISOString();
  const executable = process.platform === "win32" ? (process.env.ComSpec ?? "cmd.exe") : "pnpm";
  const args = process.platform === "win32"
    ? ["/d", "/s", "/c", `pnpm ${definition.args.join(" ")}`]
    : definition.args;
  const result = spawnSync(executable, args, {
    env: { ...process.env, DADA_EVIDENCE_DIR: evidenceDirectory },
    stdio: "inherit",
  });
  commands.push({
    command: definition.command,
    exit_code: result.status ?? 1,
    finished_at: new Date().toISOString(),
    started_at: commandStartedAt,
  });
}

const allPassed = commands.every((command) => command.exit_code === 0);
const requiredEvidence = ["dependency-tree.json", "native-smoke.json"];
const missingEvidence = requiredEvidence.filter((path) => !existsSync(resolve(evidenceDirectory, path)));
const passed = allPassed && missingEvidence.length === 0;

writeFileSync(
  resolve(evidenceDirectory, "commands.json"),
  `${JSON.stringify({ schema_version: "1.0", run_id: runId, phase: "green", commands }, null, 2)}\n`,
);

const manifestBytes = readFileSync("tasks.manifest.json");
const result = {
  schema_version: "1.0",
  run_id: runId,
  task_id: "TASK-WP0-01",
  case_id: caseId,
  parent_family: "TDD-WP0-DEP-001",
  phase: "green",
  status: passed ? "passed" : "failed",
  manifest: {
    path: "tasks.manifest.json",
    sha256: createHash("sha256").update(manifestBytes).digest("hex").toUpperCase(),
  },
  environment: {
    arch: process.arch,
    node: process.version.slice(1),
    os: process.platform,
  },
  evidence_files: ["commands.json", ...requiredEvidence],
  missing_evidence: missingEvidence,
  started_at: startedAt,
  finished_at: new Date().toISOString(),
};
writeFileSync(resolve(evidenceDirectory, "result.json"), `${JSON.stringify(result, null, 2)}\n`);

console.log(JSON.stringify(result, null, 2));
if (!passed) process.exit(1);
