import { readdirSync, readFileSync, statSync } from "node:fs";
import { extname, join, relative } from "node:path";

const scanRoots = ["apps", "packages", "scripts", "supervisor", "tests"];
const textExtensions = new Set([".cs", ".css", ".html", ".js", ".json", ".mjs", ".ts", ".tsx", ".yaml", ".yml"]);
const findings = [];

function visit(path) {
  for (const name of readdirSync(path)) {
    const child = join(path, name);
    const relativePath = relative(process.cwd(), child).replaceAll("\\", "/");
    if (["bin", "dist", "node_modules", "obj"].includes(name)) continue;
    if (statSync(child).isDirectory()) {
      visit(child);
      continue;
    }
    if (!textExtensions.has(extname(name)) || relativePath === "scripts/redaction-scan.mjs") continue;

    const content = readFileSync(child, "utf8");
    const prohibited = [
      /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/,
      /[A-Za-z]:\\Users\\[^\\\s]+/,
      /(?:api[_-]?key|password|secret)\s*[:=]\s*["'][^"']{8,}["']/i,
    ];
    if (prohibited.some((pattern) => pattern.test(content))) findings.push(relativePath);
  }
}

for (const root of scanRoots) visit(root);

console.log(JSON.stringify({ findings, status: findings.length === 0 ? "passed" : "failed" }, null, 2));
if (findings.length > 0) process.exit(1);
