#!/usr/bin/env node
// Fails (exit 1) if any reference to @skeletonlabs appears in package.json,
// package-lock.json, or anywhere under src/. Prevents a future agent
// reading "frontend overhaul" from reaching for Skeleton — see
// docs/release/v0.2-frontend-overhaul.md §16.

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

const ROOT = process.cwd();
const NEEDLE = "@skeletonlabs";
const hits = [];

function checkFile(path) {
  try {
    const content = readFileSync(path, "utf8");
    if (content.includes(NEEDLE)) {
      const rel = relative(ROOT, path);
      const lines = content.split("\n");
      for (let i = 0; i < lines.length; i++) {
        if (lines[i].includes(NEEDLE)) {
          hits.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
        }
      }
    }
  } catch {
    // unreadable -> ignore
  }
}

function walk(dir) {
  let entries;
  try {
    entries = readdirSync(dir);
  } catch {
    return;
  }
  for (const name of entries) {
    if (name === "node_modules" || name === ".svelte-kit" || name === ".git") continue;
    const full = join(dir, name);
    let st;
    try {
      st = statSync(full);
    } catch {
      continue;
    }
    if (st.isDirectory()) {
      walk(full);
    } else {
      checkFile(full);
    }
  }
}

checkFile(join(ROOT, "package.json"));
checkFile(join(ROOT, "package-lock.json"));
walk(join(ROOT, "src"));

if (hits.length > 0) {
  console.error(`guard-no-skeleton: found ${hits.length} reference(s) to ${NEEDLE}:`);
  for (const h of hits) console.error("  " + h);
  console.error("\nLumotia v0.2 frontend overhaul forbids Skeleton.");
  console.error("See docs/release/v0.2-frontend-overhaul.md §16.");
  process.exit(1);
}

console.log(`guard-no-skeleton: clean (no ${NEEDLE} references in package.json, package-lock.json, or src/)`);
