#!/usr/bin/env node
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.join(__dirname, "..");

const REQUIRED_TOP = ["schema_version", "core", "recommended", "optional"];
const TIERS = ["core", "recommended", "optional", "project_added"];

function fail(msg) {
  console.error(`registry validation error: ${msg}`);
  process.exit(1);
}

function validateRegistry(registry) {
  if (!registry || typeof registry !== "object") fail("root must be object");
  for (const key of REQUIRED_TOP) {
    if (!(key in registry)) fail(`missing top-level key: ${key}`);
  }
  if (!/^\d+\.\d+$/.test(String(registry.schema_version || ""))) {
    fail("schema_version must be major.minor (e.g. 1.1)");
  }
  const seen = new Set();
  for (const tier of TIERS) {
    const list = registry[tier];
    if (list == null) continue;
    if (!Array.isArray(list)) fail(`${tier} must be array`);
    for (const name of list) {
      if (typeof name !== "string" || !name.trim()) fail(`${tier} entry must be non-empty string`);
      if (seen.has(name)) fail(`duplicate skill name across tiers: ${name}`);
      seen.add(name);
    }
  }
  if (!registry.core.length) fail("core tier must not be empty");
  console.log(
    `registry valid (schema_version ${registry.schema_version}, ${seen.size} unique skills)`
  );
}

const registryPath = process.argv[2] || path.join(root, "registry.json");
if (!fs.existsSync(registryPath)) fail(`file not found: ${registryPath}`);
validateRegistry(JSON.parse(fs.readFileSync(registryPath, "utf-8")));
