import { readFile, readdir } from "node:fs/promises";
import path from "node:path";

const root = process.cwd();
const scanRoots = ["app", "public"];
const sourceExtensions = new Set([".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".html"]);

const prohibited = [
  { label: "Google Analytics / Tag Manager", pattern: /googletagmanager|google-analytics|\bgtag\s*\(/i },
  { label: "Vercel Analytics", pattern: /@vercel\/analytics|<Analytics\b/i },
  { label: "Vercel Speed Insights", pattern: /@vercel\/speed-insights|<SpeedInsights\b/i },
  { label: "Meta Pixel", pattern: /connect\.facebook\.net|\bfbq\s*\(/i },
  { label: "Session replay / product analytics", pattern: /hotjar|fullstory|posthog|mixpanel|amplitude|segment\.com/i },
  { label: "Cookie write", pattern: /document\.cookie\s*=/i },
  { label: "Local storage write", pattern: /localStorage\.setItem\s*\(/i },
  { label: "Session storage write", pattern: /sessionStorage\.setItem\s*\(/i },
  { label: "Beacon tracking", pattern: /navigator\.sendBeacon\s*\(/i },
  { label: "First-party HTML form", pattern: /<form\b/i },
  { label: "First-party input field", pattern: /<(input|textarea)\b/i },
  { label: "Campaign tracking parameter", pattern: /[?&](utm_[a-z_]+|gclid|fbclid)=/i },
  { label: "Amazon affiliate tag", pattern: /[?&]tag=[^&"']+/i },
];

async function walk(relative) {
  const absolute = path.join(root, relative);
  const entries = await readdir(absolute, { withFileTypes: true });
  const files = [];
  for (const entry of entries) {
    if (entry.name === ".well-known" || entry.name === "source") continue;
    const child = path.join(relative, entry.name);
    if (entry.isDirectory()) files.push(...(await walk(child)));
    else if (sourceExtensions.has(path.extname(entry.name))) files.push(child);
  }
  return files;
}

const packageJson = JSON.parse(await readFile(path.join(root, "package.json"), "utf8"));
const dependencyText = JSON.stringify({
  ...(packageJson.dependencies ?? {}),
  ...(packageJson.devDependencies ?? {}),
});

const dependencyPatterns = [
  /@vercel\/analytics/i,
  /@vercel\/speed-insights/i,
  /google-analytics/i,
  /posthog/i,
  /hotjar/i,
  /fullstory/i,
  /mixpanel/i,
  /amplitude/i,
];

const findings = [];
for (const pattern of dependencyPatterns) {
  if (pattern.test(dependencyText)) {
    findings.push(`package.json: prohibited analytics dependency matching ${pattern}`);
  }
}

for (const scanRoot of scanRoots) {
  for (const file of await walk(scanRoot)) {
    const text = await readFile(path.join(root, file), "utf8");
    for (const check of prohibited) {
      if (check.pattern.test(text)) findings.push(`${file}: ${check.label}`);
    }
  }
}

if (findings.length) {
  console.error("Privacy audit failed:\n");
  for (const finding of findings) console.error(`- ${finding}`);
  process.exit(1);
}

console.log("Privacy audit passed: no prohibited first-party tracking or collection patterns found.");
