import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, 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 ?? `wp5-03-${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}`);

const cases = [
  {
    acceptance_criteria: ["AC-32", "AC-42", "AC-48"],
    evidence: ["manifest.json", "registration-validation.json", "response.json", "trace.zip", "screenshots/allowlist.png"],
    id: "TDD-WP5-WHITE-001-p0a-allowlist",
    requirements: ["ADMIN-07", "DYN-01", "DYN-08", "NFR-02", "NFR-07", "STATIC-01", "TEXT-01", "TEXT-04"],
  },
  {
    acceptance_criteria: ["AC-15", "AC-16", "AC-32"],
    evidence: ["manifest.json", "palette.json", "pixel-diff.json", "trace.zip", "screenshots/color-cards.png"],
    id: "TDD-WP5-COL-001-four-layouts",
    requirements: ["COL-01", "COL-02", "COL-03", "COL-04", "COL-05"],
  },
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });

const whiteDirectory = resolve(casesDirectory, cases[0].id);
const colorDirectory = resolve(casesDirectory, cases[1].id);
const outputDirectory = resolve(runDirectory, "playwright-output");
const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_ASSET_RENDERER: colorDirectory,
  DADA_EVIDENCE_DIR_TEMPLATE_REGISTRY: whiteDirectory,
  DADA_PLAYWRIGHT_OUTPUT_DIR: outputDirectory,
  DADA_WP5_03_COLOR_EVIDENCE_DIR: colorDirectory,
  DADA_WP5_03_RUN_DIRECTORY: runDirectory,
  DADA_WP5_03_WHITE_EVIDENCE_DIR: whiteDirectory,
};

const commands = phase === "red"
  ? [["red-unit", "pnpm exec vitest run tests/unit/wp5-03-template-registry.test.ts"]]
  : [
    ["build-template-registry", "pnpm --filter @dada/template-registry build"],
    ["build-asset-renderer", "pnpm --filter @dada/asset-renderer build"],
    ["build-static-catalog", "pnpm --filter @dada/static-sticker-catalog build"],
    ["build-asset-compiler", "pnpm --filter @dada/asset-compiler build"],
    ["compile-real-archive", "node scripts/compile-wp5-03-assets.mjs"],
    ["unit", "pnpm test:unit"],
    ["e2e", "pnpm test:e2e"],
    ["visual", "pnpm test:visual"],
    ["performance", "pnpm test:performance"],
    ["api", "pnpm test:api"],
    ["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, maxBuffer: 40 * 1024 * 1024,
  });
  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 === "green" && (result.status ?? 1) !== 0) break;
}

function findFiles(directory, name) {
  const matches = [];
  if (!existsSync(directory)) return matches;
  for (const entry of readdirSync(directory, { withFileTypes: true })) {
    const path = resolve(directory, entry.name);
    if (entry.isDirectory()) matches.push(...findFiles(path, name));
    else if (entry.name === name) matches.push(path);
  }
  return matches;
}

if (phase === "green") {
  const traces = findFiles(outputDirectory, "trace.zip");
  const whiteTrace = traces.find((path) => path.toLowerCase().includes("wp5-white-001") || path.toLowerCase().includes("p0-a-public-allowlist"));
  const colorTrace = traces.find((path) => path.toLowerCase().includes("wp5-col-001") || path.toLowerCase().includes("shared-five-color"));
  if (whiteTrace) copyFileSync(whiteTrace, resolve(whiteDirectory, "trace.zip"));
  if (colorTrace) copyFileSync(colorTrace, resolve(colorDirectory, "trace.zip"));
}

const redConfirmed = phase === "red" && commandResults.length === 1 && commandResults[0].exit_code !== 0;
if (phase === "red") {
  const observation = {
    expected_failure: "template-registry and asset-renderer modules are absent before TASK-WP5-03",
    observed_command: commandResults[0].command,
    observed_exit_code: commandResults[0].exit_code,
    status: redConfirmed ? "red_confirmed" : "failed",
  };
  for (const item of cases) writeFileSync(resolve(casesDirectory, item.id, "red-observation.json"), `${JSON.stringify(observation, null, 2)}\n`);
}

const commandState = phase === "red" ? redConfirmed : commandResults.length === commands.length && 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);
  const evidenceRefs = phase === "red" ? ["red-observation.json"] : item.evidence;
  const missingEvidence = evidenceRefs.filter((file) => !existsSync(resolve(directory, file)));
  const status = commandState && missingEvidence.length === 0 ? phase === "red" ? "red_confirmed" : "passed" : "failed";
  writeFileSync(resolve(directory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
  writeFileSync(resolve(directory, "result.json"), `${JSON.stringify({
    acceptance_criteria: item.acceptance_criteria,
    automation: ["automated"],
    commit,
    evidence_refs: evidenceRefs,
    layer: ["UNIT", "E2E", "VIS-PERF", "API"],
    layer_notes: {
      API: "The frozen API regression is required; WP5-04 owns the public resource routes.",
      PERFORMANCE: "The focused browser case records bounded DOM and canvas evidence; the current root runner reports not_applicable for TASK-WP0-01.",
      VISUAL: "The focused browser case records screenshots and canvas pixel evidence; the current root runner reports not_applicable for TASK-WP0-01.",
    },
    manifest,
    missing_evidence: missingEvidence,
    phase,
    requirements: item.requirements,
    run_id: runId,
    status,
    task_id: "TASK-WP5-03",
    test_id: item.id,
    work_package: "WP-5",
    worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
  }, null, 2)}\n`);
  summaries.push({ missing_evidence: missingEvidence, status, test_id: item.id });
}
const status = summaries.every((item) => item.status === (phase === "red" ? "red_confirmed" : "passed"))
  ? phase === "red" ? "red_confirmed" : "passed"
  : "failed";
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
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 === "failed") process.exit(1);
