import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, statSync, 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 ?? `wp2-01-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const casesRoot = resolve(runDirectory, "cases");
const playwrightDirectory = resolve(runDirectory, "playwright");
const caseIds = [
  "TDD-WP2-PROJ-001-new-versus-continue",
  "TDD-WP2-PROJ-005-failed-draft-retry",
];
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
for (const caseId of caseIds) mkdirSync(resolve(casesRoot, caseId), { recursive: true });

const commandsToRun = phase === "red"
  ? [
      ["project-integration", ["exec", "vitest", "run", "tests/integration/wp2-01-projects.test.ts"]],
      ["project-api", ["exec", "vitest", "run", "tests/api/wp2-01-projects.test.ts"]],
      ["project-e2e", ["exec", "playwright", "test", "tests/e2e/projects-workspace.spec.ts", "--config", "playwright.config.ts"]],
    ]
  : [
      ["integration", ["test:integration"]],
      ["api", ["test:api"]],
      ["e2e", ["test:e2e"]],
      ["tdd-trace", ["validate:tdd-trace"]],
    ];
const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_PROJECTS: casesRoot,
  DADA_PLAYWRIGHT_OUTPUT_DIR: playwrightDirectory,
};
const commandResults = [];
for (const [name, args] of commandsToRun) {
  const command = `pnpm ${args.join(" ")}`;
  const started_at = new Date().toISOString();
  const execution = spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], { encoding: "utf8", env: environment });
  if (execution.stdout) process.stdout.write(execution.stdout);
  if (execution.stderr) process.stderr.write(execution.stderr);
  commandResults.push({ command, exit_code: execution.status ?? 1, finished_at: new Date().toISOString(), name, started_at });
}

function find(root, name) {
  if (!existsSync(root)) return [];
  return readdirSync(root).flatMap((entry) => {
    const child = resolve(root, entry);
    return statSync(child).isDirectory() ? find(child, name) : entry === name ? [child] : [];
  });
}

if (phase === "green") {
  const traces = find(playwrightDirectory, "trace.zip");
  const projectTrace = traces.find((path) => path.includes("inventing-a-model"))
    ?? traces.find((path) => path.includes("project-detail"));
  const draftTrace = traces.find((path) => path.includes("project-list"));
  if (projectTrace) copyFileSync(projectTrace, resolve(casesRoot, caseIds[0], "trace.zip"));
  if (draftTrace) copyFileSync(draftTrace, resolve(casesRoot, caseIds[1], "trace.zip"));
}

for (const caseId of caseIds) {
  writeFileSync(resolve(casesRoot, caseId, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
}
const expectedEvidence = phase === "red" ? ["red-observation.json"] : ["response.json", "db-diff.json", "trace.zip"];
const commandState = phase === "red"
  ? commandResults.every((result) => result.exit_code !== 0)
  : commandResults.every((result) => result.exit_code === 0);
if (phase === "red") {
  for (const caseId of caseIds) {
    writeFileSync(resolve(casesRoot, caseId, "red-observation.json"), `${JSON.stringify({
      expected_failure: caseId.includes("PROJ-001")
        ? "new and continued generation project semantics plus fixed history rules are absent"
        : "failed-empty retry and batch eligibility semantics are absent",
      status: commandState ? "red_confirmed" : "failed",
    }, 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 results = caseIds.map((testId) => {
  const directory = resolve(casesRoot, testId);
  const evidence_refs = expectedEvidence;
  const missing_evidence = evidence_refs.filter((file) => !existsSync(resolve(directory, file)));
  const status = commandState && missing_evidence.length === 0 ? (phase === "red" ? "red_confirmed" : "passed") : "failed";
  const result = {
    acceptance_criteria: testId.includes("PROJ-001") ? ["AC-03", "AC-06", "AC-34"] : ["AC-04", "AC-43"],
    automation: ["automated"], commit, evidence_refs, layer: ["DB", "API", "E2E"], manifest,
    missing_evidence, phase,
    requirements: testId.includes("PROJ-001") ? ["GEN-04", "GEN-11", "PROJECT-01", "PROJECT-02", "PROJECT-03"] : ["GEN-09", "PROJECT-01"],
    run_id: runId, status, task_id: "TASK-WP2-01", test_id: testId, work_package: "WP-2",
    worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
  };
  writeFileSync(resolve(directory, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
  return result;
});
const targetStatus = phase === "red" ? "red_confirmed" : "passed";
const passed = results.every((result) => result.status === targetStatus);
const summary = {
  cases: results.map(({ missing_evidence, status, test_id }) => ({ missing_evidence, status, test_id })),
  phase, run_id: runId, status: passed ? targetStatus : "failed",
};
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify(summary, null, 2)}\n`);
console.log(JSON.stringify(summary, null, 2));
if (!passed) process.exit(1);
