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

const phaseIndex = process.argv.indexOf("--phase");
const phase = phaseIndex >= 0 ? process.argv[phaseIndex + 1] : "green";
if (!new Set(["red", "green"]).has(phase)) throw new Error(`Unsupported phase: ${phase}`);

const runId = process.env.DADA_TDD_RUN_ID ?? `wp6-04-${phase}-${new Date().toISOString().replace(/[^0-9]/g, "")}`;
const runDirectory = resolve("artifacts", "tdd", runId);
const caseDirectory = resolve(runDirectory, "cases", "TDD-WP6-AUD-001-sensitive-operations");
const replicationRoot = resolve(process.env.DADA_REPLICATION_ASSET_ROOT ?? join(homedir(), "Desktop", "sticker_web_replication_assets"));
if (existsSync(runDirectory)) throw new Error(`Evidence run already exists: ${runId}`);
mkdirSync(caseDirectory, { recursive: true });

const environment = {
  ...process.env,
  DADA_EVIDENCE_DIR_WP6_AUD: caseDirectory,
  DADA_PLAYWRIGHT_OUTPUT_DIR: resolve(runDirectory, "playwright-output"),
  DADA_STATIC_STICKER_ROOT: process.env.DADA_STATIC_STICKER_ROOT ?? join(replicationRoot, "sticker_normal"),
  DADA_DYNAMIC_ASSET_ROOT: process.env.DADA_DYNAMIC_ASSET_ROOT ?? join(replicationRoot, "sticker_interactive", "单模板归档", "templates"),
  DADA_TEXT_ASSET_ROOT: process.env.DADA_TEXT_ASSET_ROOT ?? join(replicationRoot, "sticker_text"),
};
const commands = phase === "red"
  ? [
      ["integration-red", ".\\node_modules\\.bin\\vitest.CMD run tests/integration/wp6-04-sensitive-audit.test.ts tests/integration/wp5-05-sticker-release.test.ts"],
      ["api-red", ".\\node_modules\\.bin\\vitest.CMD run tests/api/wp6-04-audit.test.ts"],
      ["e2e-red", ".\\node_modules\\.bin\\playwright.CMD test tests/e2e/wp6-04-audit.spec.ts --config playwright.config.ts"],
    ]
  : [
      ["integration", "pnpm.cmd exec vitest run tests/integration --testTimeout=20000"],
      ["api", "pnpm.cmd check:openapi && pnpm.cmd exec vitest run tests/api --testTimeout=20000"],
      ["worker", "pnpm.cmd test:worker"],
      ["e2e", "pnpm.cmd test:e2e"],
      ["tdd-trace", "pnpm.cmd 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) {
  if (!existsSync(directory)) return [];
  return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
    const path = resolve(directory, entry.name);
    return entry.isDirectory() ? findFiles(path, name) : entry.name === name ? [path] : [];
  });
}

const trace = findFiles(environment.DADA_PLAYWRIGHT_OUTPUT_DIR, "trace.zip")
  .find((path) => path.toLowerCase().includes("wp6-04-audit"));
if (trace) copyFileSync(trace, resolve(caseDirectory, "trace.zip"));

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: "Audit list APIs and UI are absent, while invite, user-status, and sticker-release mutations are missing same-transaction AdminOperationLog coverage.",
    observed_commands: commandResults,
    red_reason: "TDD-WP6-AUD-001 first Red: required operations can be missing audit rows, the two log types have no separate admin read contract, and no admin audit page exists.",
    status: redConfirmed ? "red_confirmed" : "failed",
  }, null, 2)}\n`);
}

const expectedEvidence = phase === "red"
  ? ["red-observation.json"]
  : ["operation-matrix.json", "db-diff.json", "redaction.json", "trace.zip"];
const missingEvidence = expectedEvidence.filter((file) => !existsSync(resolve(caseDirectory, file)));
const greenPassed = phase === "green" && commandResults.length === commands.length && commandResults.every((item) => item.exit_code === 0);
const status = phase === "red"
  ? redConfirmed && missingEvidence.length === 0 ? "red_confirmed" : "failed"
  : greenPassed && missingEvidence.length === 0 ? "green" : "failed";
const result = {
  acceptance_criteria: ["AC-50"],
  automation: ["automated"],
  commit: spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim(),
  evidence_refs: expectedEvidence,
  layer: ["DB", "API", "WRK", "E2E"],
  manifest: {
    path: "tasks.manifest.json",
    sha256: createHash("sha256").update(readFileSync("tasks.manifest.json")).digest("hex").toUpperCase(),
  },
  missing_evidence: missingEvidence,
  phase,
  requirements: ["ADMIN-09"],
  run_id: runId,
  status,
  task_id: "TASK-WP6-04",
  test_id: "TDD-WP6-AUD-001-sensitive-operations",
  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);
