const fs = require("fs");
const path = require("path");

const REGISTRY_FILE = "registry.json";

function loadRegistry(rootDir) {
  const file = path.join(rootDir, REGISTRY_FILE);
  if (!fs.existsSync(file)) return { error: "registry.json not found — run capint init" };
  try {
    return { registry: JSON.parse(fs.readFileSync(file, "utf-8")) };
  } catch (e) {
    return { error: `registry.json parse error: ${e.message}` };
  }
}

function backupRegistry(rootDir) {
  const file = path.join(rootDir, REGISTRY_FILE);
  const backupDir = path.join(rootDir, ".capint", "backups");
  fs.mkdirSync(backupDir, { recursive: true });
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
  const backupPath = path.join(backupDir, `registry.${stamp}.json`);
  fs.copyFileSync(file, backupPath);
  return backupPath;
}

function saveRegistry(rootDir, registry) {
  const file = path.join(rootDir, REGISTRY_FILE);
  fs.writeFileSync(file, `${JSON.stringify(registry, null, 2)}\n`, "utf-8");
}

function pinSkill(rootDir, name) {
  const normalized = name.trim();
  if (!normalized) return { error: "skill name required" };

  const skillPath = path.join(rootDir, "skills", normalized, "SKILL.md");
  if (!fs.existsSync(skillPath)) {
    return {
      error: `Skill not on disk: skills/${normalized}/SKILL.md — run capint init or copy skill first`
    };
  }

  const loaded = loadRegistry(rootDir);
  if (loaded.error) return loaded;
  const registry = loaded.registry;

  for (const tier of ["core", "recommended", "optional", "project_added"]) {
    registry[tier] = registry[tier] || [];
  }

  if ((registry.core || []).includes(normalized)) {
    return { error: `Cannot pin core skill "${normalized}" — already in core tier` };
  }

  const alreadyPinned = (registry.project_added || []).includes(normalized);
  if (alreadyPinned) {
    return { ok: true, name: normalized, tier: "project_added", already: true, registry };
  }

  registry.optional = registry.optional.filter((n) => n !== normalized);
  registry.recommended = registry.recommended.filter((n) => n !== normalized);
  if (!registry.project_added.includes(normalized)) {
    registry.project_added.push(normalized);
    registry.project_added.sort();
  }

  const backup = backupRegistry(rootDir);
  saveRegistry(rootDir, registry);

  return {
    ok: true,
    name: normalized,
    tier: "project_added",
    already: false,
    backup,
    registry
  };
}

module.exports = { loadRegistry, saveRegistry, pinSkill, backupRegistry };
