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-04-${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-42", "AC-48"],
    evidence: ["response.json", "headers.json", "cache-enumeration.json", "trace.zip"],
    id: "TDD-WP5-RES-001-three-access-classes",
    red_reason: "公开 manifest 暴露 internal/private、路径可推导或缓存策略混用",
    requirements: ["PRIV-02", "PRIV-05"],
  },
  {
    acceptance_criteria: ["AC-46", "AC-48"],
    evidence: ["cache-enumeration.json", "service-worker.json", "trace.zip"],
    id: "TDD-WP5-CACHE-001-no-private-client-state",
    red_reason: "SW 拦截 internal/private 或 IndexedDB 保存私有字段",
    requirements: ["NFR-07", "PRIV-02"],
  },
];
for (const item of cases) mkdirSync(resolve(casesDirectory, item.id), { recursive: true });

const resourceDirectory = resolve(casesDirectory, cases[0].id);
const cacheDirectory = resolve(casesDirectory, cases[1].id);
const outputDirectory = resolve(runDirectory, "playwright-output");
const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_WP5_CACHE: cacheDirectory,
  DADA_EVIDENCE_DIR_WP5_RES: resourceDirectory,
  DADA_PLAYWRIGHT_OUTPUT_DIR: outputDirectory,
};
const commands = phase === "red"
  ? [["red-focused", "pnpm --filter @dada/shared-contracts build && pnpm exec vitest run tests/unit/wp5-04-asset-release-manifest.test.ts tests/api/wp5-04-asset-access.test.ts"]]
  : [
    ["build-manifest", "pnpm --filter @dada/asset-release-manifest build"],
    ["unit", "pnpm test:unit"],
    ["api", "pnpm test:api"],
    ["e2e", "pnpm test:e2e"],
    ["security", "pnpm test:security"],
    ["package", "pnpm test:package"],
    ["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 trace = findFiles(outputDirectory, "trace.zip").find((path) => path.toLowerCase().includes("wp5-04"));
  if (trace) {
    copyFileSync(trace, resolve(resourceDirectory, "trace.zip"));
    copyFileSync(trace, resolve(cacheDirectory, "trace.zip"));
  }
}

const redConfirmed = phase === "red" && commandResults.length === 1 && commandResults[0].exit_code !== 0;
if (phase === "red") {
  for (const item of cases) {
    writeFileSync(resolve(casesDirectory, item.id, "red-observation.json"), `${JSON.stringify({
      expected_failure: item.red_reason,
      observed_command: commandResults[0].command,
      observed_exit_code: commandResults[0].exit_code,
      status: redConfirmed ? "red_confirmed" : "failed",
    }, 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", "API", "E2E", "PKG-SEC"],
    manifest,
    missing_evidence: missingEvidence,
    phase,
    red_reason: item.red_reason,
    requirements: item.requirements,
    run_id: runId,
    status,
    task_id: "TASK-WP5-04",
    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);
