#!/usr/bin/env node
/**
 * emit-all.mjs — Compliance artifact orchestrator.
 *
 * Default: regenerates all three compliance artifacts (write mode).
 * --check: diffs each artifact against the committed file; exits non-zero
 *          if any generator reports a mismatch or validation failure.
 *
 * Usage:
 *   node scripts/compliance/emit-all.mjs           # regenerate all artifacts
 *   node scripts/compliance/emit-all.mjs --check   # drift check (CI gate)
 *   pnpm compliance:emit-all
 *   pnpm compliance:emit-all --check
 */

import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import path from "node:path";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const SCRIPTS = [
  "emit-data-map.mjs",
  "emit-retention-policy.mjs",
  "emit-sub-processors.mjs",
];

const checkMode = process.argv.includes("--check");
const subArgs = checkMode ? ["--check"] : [];

let anyFailed = false;

for (const script of SCRIPTS) {
  const scriptPath = path.join(__dirname, script);
  const result = spawnSync(process.execPath, [scriptPath, ...subArgs], {
    stdio: "inherit",
  });

  if (result.status !== 0) {
    anyFailed = true;
  }
}

if (anyFailed) {
  if (checkMode) {
    process.stderr.write(
      "\n✗ compliance:emit-all — one or more artifacts are out of date.\n" +
        "  Run `pnpm compliance:emit-all` to regenerate.\n",
    );
  } else {
    process.stderr.write(
      "\n✗ compliance:emit-all — one or more artifacts failed to generate.\n",
    );
  }
  process.exit(1);
}

if (checkMode) {
  console.log("✓ compliance:emit-all — all artifacts are up to date");
} else {
  console.log("✓ compliance:emit-all — all artifacts regenerated");
}
