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] : "scaffold";
if (!new Set(["red", "scaffold"]).has(phase)) throw new Error(`Unsupported phase: ${phase}`);

const runId = process.env.DADA_TDD_RUN_ID ?? `wp6-01-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP6-ADM-001-role-and-summary");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });

const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_ADMIN: caseDirectory,
  DADA_PLAYWRIGHT_OUTPUT_DIR: resolve(runDirectory, "playwright-output"),
  DADA_WP6_01_EVIDENCE_DIR: caseDirectory,
};
const commands = phase === "red"
  ? [
      ["api-red", "pnpm exec vitest run tests/api/wp6-01-admin-shell.test.ts"],
      ["e2e-red", "pnpm exec playwright test tests/e2e/wp6-01-admin-shell.spec.ts --config playwright.config.ts"],
    ]
  : [
      ["api", "pnpm test:api"],
      ["e2e", "pnpm test:e2e"],
      ["security", "pnpm test:security"],
      ["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 === "scaffold" && (result.status ?? 1) !== 0) break;
}

const redConfirmed = phase === "red" && commandResults.length === commands.length && commandResults.every((item) => item.exit_code !== 0);
if (phase === "red") {
  writeFileSync(resolve(caseDirectory, "red-observation.json"), `${JSON.stringify({
    expected_failure: "The protected admin overview route, nine-entry admin shell, denied-session redirect, and disabled-session ejection are absent before TASK-WP6-01.",
    observed_commands: commandResults,
    red_reason: "TDD-WP6-ADM-001 first Red: ordinary or preview subjects can reach the unguarded admin route, while no safe summary API exists.",
    status: redConfirmed ? "red_confirmed" : "failed",
  }, null, 2)}\n`);
}

function findFiles(directory, name) {
  if (!existsSync(directory)) return [];
  const 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 === "scaffold") {
  const trace = findFiles(environment.DADA_PLAYWRIGHT_OUTPUT_DIR, "trace.zip")
    .find((path) => path.toLowerCase().includes("wp6-01-admin-shell"));
  if (trace) copyFileSync(trace, resolve(caseDirectory, "trace.zip"));
}

const expectedEvidence = phase === "red"
  ? ["red-observation.json"]
  : ["response.json", "db-access.json", "trace.zip", "screenshots/admin-denied.png", "screenshots/admin-overview.png"];
const missingEvidence = expectedEvidence.filter((file) => !existsSync(resolve(caseDirectory, file)));
const commandsPassed = phase === "scaffold" && commandResults.length === commands.length && commandResults.every((item) => item.exit_code === 0);
const status = phase === "red"
  ? redConfirmed && missingEvidence.length === 0 ? "red_confirmed" : "failed"
  : commandsPassed && missingEvidence.length === 0 ? "red" : "failed";
const commit = spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim();
const wp5BaselineSha = spawnSync("git", ["rev-parse", "origin/codex/wp5-04"], { encoding: "utf8" }).stdout.trim();
const manifest = {
  path: "tasks.manifest.json",
  sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase(),
};
const result = {
  acceptance_criteria: ["AC-25", "AC-49"],
  automation: ["automated"],
  commit,
  dependency_gate: {
    blocked_by: ["TASK-WP5-05", "TASK-WP5-06", "TASK-WP5-07"],
    baseline_remote_branch: "origin/codex/wp5-04",
    baseline_remote_sha: wp5BaselineSha,
    final_green_allowed: false,
  },
  evidence_refs: expectedEvidence,
  layer: ["API", "E2E"],
  manifest,
  missing_evidence: missingEvidence,
  phase,
  requirements: ["ADMIN-01", "ADMIN-02", "ADMIN-04", "ADMIN-08"],
  run_id: runId,
  status,
  task_id: "TASK-WP6-01",
  test_id: "TDD-WP6-ADM-001-role-and-summary",
  work_package: "WP-6",
};
writeFileSync(resolve(caseDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(caseDirectory, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify({ cases: [{ missing_evidence: missingEvidence, status, test_id: result.test_id }], phase, run_id: runId, status }, null, 2)}\n`);
console.log(JSON.stringify({ phase, run_id: runId, status }, null, 2));
if (status === "failed") process.exit(1);
