import { existsSync, readFileSync } from "node:fs";
import console from "node:console";
import { resolve } from "node:path";
import process from "node:process";

const root = resolve(import.meta.dirname, "..");
const mapPath = resolve(root, "docs/SECURITY-ASVS-5.md");
const source = readFileSync(mapPath, "utf8");
const requiredIds = [
  "v5.0.0-1.1.2",
  "v5.0.0-1.2.1",
  "v5.0.0-1.2.3",
  "v5.0.0-1.2.4",
  "v5.0.0-1.3.6",
  "v5.0.0-3.3.1",
  "v5.0.0-3.3.2",
  "v5.0.0-3.3.4",
  "v5.0.0-3.4.1",
  "v5.0.0-3.4.2",
  "v5.0.0-3.4.6",
  "v5.0.0-3.5.1",
  "v5.0.0-3.7.2",
  "v5.0.0-16.2.5",
  "v5.0.0-16.3.1",
  "v5.0.0-16.3.2",
];

const missingIds = requiredIds.filter((id) => !source.includes(`\`${id}\``));
const evidence = [...source.matchAll(/`((?:packages|scripts)\/[\w./-]+)`/g)].map(
  (match) => match[1],
);
const missingEvidence = evidence.filter((path) => !existsSync(resolve(root, path)));
if (missingIds.length || missingEvidence.length) {
  if (missingIds.length) console.error(`Missing ASVS mappings: ${missingIds.join(", ")}`);
  if (missingEvidence.length)
    console.error(`Missing security evidence: ${missingEvidence.join(", ")}`);
  process.exit(1);
}
console.log(
  `Security map verified: ${requiredIds.length} ASVS requirements, ${evidence.length} evidence files.`,
);
