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

const OVERLAY_PATH = ".capint/disabled-skills.json";
/** Fail-closed sentinel when overlay JSON is corrupt */
const OVERLAY_FAIL_CLOSED = "*";

function overlayFile(rootDir) {
  return path.join(rootDir, OVERLAY_PATH);
}

function loadDisabledSkills(rootDir) {
  const file = overlayFile(rootDir);
  if (!fs.existsSync(file)) {
    return { schema_version: "1.0", disabled: [], log: [] };
  }
  try {
    const data = JSON.parse(fs.readFileSync(file, "utf-8"));
    return {
      schema_version: data.schema_version || "1.0",
      disabled: [...new Set(data.disabled || [])],
      log: Array.isArray(data.log) ? data.log : []
    };
  } catch {
    return { schema_version: "1.0", disabled: [], log: [], parseError: true };
  }
}

function disabledSet(rootDir) {
  const data = loadDisabledSkills(rootDir);
  if (data.parseError) {
    return new Set([OVERLAY_FAIL_CLOSED]);
  }
  return new Set(data.disabled);
}

function overlayParseError(rootDir) {
  return Boolean(loadDisabledSkills(rootDir).parseError);
}

function writeOverlay(rootDir, data) {
  const file = overlayFile(rootDir);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`, "utf-8");
}

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

  const data = loadDisabledSkills(rootDir);
  if (!data.disabled.includes(normalized)) {
    data.disabled.push(normalized);
    data.disabled.sort();
  }
  data.log.push({ action: "disable", name: normalized, at: new Date().toISOString() });
  writeOverlay(rootDir, data);
  return { ok: true, name: normalized, disabled: data.disabled };
}

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

  const data = loadDisabledSkills(rootDir);
  data.disabled = data.disabled.filter((n) => n !== normalized);
  data.log.push({ action: "enable", name: normalized, at: new Date().toISOString() });
  writeOverlay(rootDir, data);
  return { ok: true, name: normalized, disabled: data.disabled };
}

function listDisabledSkills(rootDir) {
  const data = loadDisabledSkills(rootDir);
  return { disabled: data.disabled, count: data.disabled.length, parseError: Boolean(data.parseError) };
}

module.exports = {
  OVERLAY_PATH,
  OVERLAY_FAIL_CLOSED,
  loadDisabledSkills,
  disabledSet,
  overlayParseError,
  disableSkill,
  enableSkill,
  listDisabledSkills
};
