import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { spawnSync } from "node:child_process";

const phaseIndex = process.argv.indexOf("--phase");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
const manualReviewed = process.argv.includes("--manual-reviewed");
if (!["red", "green"].includes(phase)) throw new Error(`Unsupported phase: ${phase}`);
const runId = process.env.DADA_TDD_RUN_ID ?? `wp5-02-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP5-CAT-001-catalog-1407");
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });

const sourceRoot = process.env.DADA_STATIC_STICKER_ROOT ?? join(homedir(), "Desktop", "贴纸素材");
const environment = { ...process.env, DADA_EVIDENCE_DIR_STATIC_STICKER: caseDirectory };
const commands = phase === "red" ? [] : [
  ["build-static-catalog-contract", "pnpm --filter @dada/static-sticker-catalog build"],
  ["build-asset-compiler", "pnpm --filter @dada/asset-compiler build"],
  ["compile-readonly-catalog", `node packages/asset-compiler/dist/cli.js --catalog --source-root "${sourceRoot}" --output "${caseDirectory}" --release-version p0a-static-v1 --expected-count 1407`],
  ["unit", "pnpm test:unit"],
  ["e2e", "pnpm test:e2e"],
  ["tdd-trace", "pnpm validate:tdd-trace"],
];
const commandResults = [];
for (const [name, command] of commands) {
  const started_at = new Date().toISOString();
  const result = name === "compile-readonly-catalog"
    ? spawnSync(process.execPath, ["packages/asset-compiler/dist/cli.js", "--catalog", "--source-root", sourceRoot, "--output", caseDirectory, "--release-version", "p0a-static-v1", "--expected-count", "1407"], { encoding: "utf8", env: environment, maxBuffer: 20 * 1024 * 1024 })
    : spawnSync(process.env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", command], { encoding: "utf8", env: environment, maxBuffer: 20 * 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 ((result.status ?? 1) !== 0) break;
}

if (phase === "red") {
  writeFileSync(resolve(caseDirectory, "red-observation.json"), `${JSON.stringify({
    expected_failure: "static sticker catalog compiler and virtual list contract are not implemented",
    observed_command: "pnpm exec vitest run tests/unit/wp5-02-static-sticker-catalog.test.ts",
    observed_error: "Cannot find module packages/static-sticker-catalog/src/index.js",
    status: "red_confirmed",
  }, null, 2)}\n`);
}

const automaticEvidence = [
  "static-sticker-catalog.json", "catalog-validation.json", "compiler-report.json", "source-before.json", "source-after.json",
  "source-hashes.json", "network-timeline.json", "dom-count.json", "ui-catalog-validation.json",
];
if (phase !== "red" && existsSync(resolve(caseDirectory, "source-before.json")) && existsSync(resolve(caseDirectory, "source-after.json"))) {
  const before = JSON.parse(readFileSync(resolve(caseDirectory, "source-before.json"), "utf8"));
  const after = JSON.parse(readFileSync(resolve(caseDirectory, "source-after.json"), "utf8"));
  const unchanged = JSON.stringify(before) === JSON.stringify(after);
  writeFileSync(resolve(caseDirectory, "source-hashes.json"), `${JSON.stringify({ files: before.files?.length ?? 0, sha256_and_mtime_unchanged: unchanged, schema_version: "static-sticker-source-hashes/v1" }, null, 2)}\n`);
}
const missing = phase === "red" ? [] : automaticEvidence.filter((file) => !existsSync(resolve(caseDirectory, file)));
const commandState = phase === "red" || commandResults.length > 0 && commandResults.every((result) => result.exit_code === 0);
const status = phase === "red"
  ? commandState && missing.length === 0 ? "red_confirmed" : "failed"
  : !commandState || missing.length > 0 ? "failed" : manualReviewed ? "passed" : "awaiting_manual_review";
const manualReview = manualReviewed
  ? { checks: ["目录计数与 part1-25、三组重复哈希已确认", "滚动目录时 DOM 节点保持视口与两屏缓冲范围", "面板打开不请求原图，加入画布后才请求原图"], reviewer: "user_confirmation", status: "passed" }
  : { checks: ["目录计数与 part1-25、三组重复哈希已确认", "滚动目录时 DOM 节点保持视口与两屏缓冲范围", "面板打开不请求原图，加入画布后才请求原图"], reviewer: "human_required", status: "pending" };
writeFileSync(resolve(caseDirectory, "manual-review.json"), `${JSON.stringify(manualReview, 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;
writeFileSync(resolve(caseDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(caseDirectory, "result.json"), `${JSON.stringify({
  acceptance_criteria: ["AC-13", "AC-32"], automation: ["automated", "manual_review"], commit, evidence_refs: [...automaticEvidence, "manual-review.json"],
  layer: ["UNIT", "E2E", "MANUAL"], manifest, missing_evidence: missing, phase, requirements: ["STATIC-01", "STATIC-02", "STATIC-03", "STATIC-04"],
  run_id: runId, status, task_id: "TASK-WP5-02", test_id: "TDD-WP5-CAT-001-catalog-1407", work_package: "WP-5", worktree_under_test: dirty ? "uncommitted implementation" : "clean committed implementation",
}, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "commands.json"), `${JSON.stringify({ commands: commandResults, phase, run_id: runId }, null, 2)}\n`);
writeFileSync(resolve(runDirectory, "evidence.json"), `${JSON.stringify({ cases: [{ missing_evidence: missing, status, test_id: "TDD-WP5-CAT-001-catalog-1407" }], phase, run_id: runId, status }, null, 2)}\n`);
console.log(JSON.stringify({ cases: [{ missing_evidence: missing, status, test_id: "TDD-WP5-CAT-001-catalog-1407" }], phase, run_id: runId, status }, null, 2));
if (status === "failed") process.exit(1);
