"use strict";

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

const { GLOBAL_CLAUDE_DIR, SAFETY_HOOK_FILENAMES } = require("./constants");

function isSafetyHook(command) {
  if (typeof command !== "string") return false;
  return SAFETY_HOOK_FILENAMES.some((name) => command.includes(name));
}

function isHookPresent(settings, def) {
  if (!settings || !settings.hooks || !settings.hooks[def.event]) return false;
  const groups = settings.hooks[def.event];
  if (!Array.isArray(groups)) return false;
  for (const group of groups) {
    if (!group) continue;
    if (Array.isArray(group.hooks)) {
      if (
        group.hooks.some(
          (h) =>
            typeof h.command === "string" && h.command.includes(def.filename),
        )
      )
        return true;
    } else if (
      group.type === "command" &&
      typeof group.command === "string" &&
      group.command.includes(def.filename)
    ) {
      return true;
    }
  }
  return false;
}

function injectHook(settings, def) {
  if (!settings.hooks) settings.hooks = {};
  if (!settings.hooks[def.event]) settings.hooks[def.event] = [];

  const groups = settings.hooks[def.event];
  const hookEntry = { type: "command", command: def.commandTemplate };

  // Find existing matcher group with matching matcher string
  for (const group of groups) {
    if (!group || !Array.isArray(group.hooks)) continue;
    const groupMatcher = group.matcher || "";
    if (groupMatcher === def.matcher) {
      // Prepend safety hook (safety hooks run first)
      group.hooks.unshift(hookEntry);
      return;
    }
  }

  // No matching group found — create new one and prepend it
  const newGroup = { matcher: def.matcher, hooks: [hookEntry] };
  groups.unshift(newGroup);
}

/**
 * Read protectionsEnabled from global-state.json.
 * Returns true/false. Defaults to false if file/field missing.
 */
function readProtectionState(globalDir = GLOBAL_CLAUDE_DIR) {
  const statePath = path.join(
    globalDir,
    "evolv-coder-kit",
    "global-state.json",
  );
  try {
    const state = JSON.parse(fs.readFileSync(statePath, "utf-8"));
    return state.protectionsEnabled === true;
  } catch {
    return false; // default: protections off
  }
}

/**
 * Write protectionsEnabled to global-state.json (merges with existing state).
 */
function writeProtectionState(
  enabled,
  { dryRun = false, globalDir = GLOBAL_CLAUDE_DIR } = {},
) {
  const statePath = path.join(
    globalDir,
    "evolv-coder-kit",
    "global-state.json",
  );
  if (dryRun) return;

  let state = {};
  try {
    state = JSON.parse(fs.readFileSync(statePath, "utf-8"));
  } catch {
    /* start fresh */
  }

  state.protectionsEnabled = enabled;
  // Clean up legacy protectionState field if present
  delete state.protectionState;

  fs.mkdirSync(path.dirname(statePath), { recursive: true });
  const content = JSON.stringify(state, null, 2) + "\n";
  fs.writeFileSync(statePath + ".tmp", content, "utf-8");
  fs.renameSync(statePath + ".tmp", statePath);
}

function disableProtections({
  dryRun = false,
  globalDir = GLOBAL_CLAUDE_DIR,
} = {}) {
  const currentState = readProtectionState(globalDir);

  if (!currentState) {
    return { success: true, message: "Protections already disabled" };
  }

  if (dryRun) {
    return {
      success: true,
      message:
        "dry-run: would set protectionsEnabled=false in global-state.json",
    };
  }

  writeProtectionState(false, { globalDir });
  return {
    success: true,
    message: "Protections disabled. Safety hooks will NOOP until re-enabled.",
  };
}

function enableProtections({
  dryRun = false,
  globalDir = GLOBAL_CLAUDE_DIR,
} = {}) {
  const currentState = readProtectionState(globalDir);

  if (currentState) {
    return { success: true, message: "Protections already enabled" };
  }

  if (dryRun) {
    return {
      success: true,
      message:
        "dry-run: would set protectionsEnabled=true in global-state.json",
    };
  }

  writeProtectionState(true, { globalDir });
  return {
    success: true,
    message: "Protections enabled. Safety hooks are now active.",
  };
}

module.exports = {
  isSafetyHook,
  isHookPresent,
  injectHook,
  readProtectionState,
  writeProtectionState,
  disableProtections,
  enableProtections,
};
