globalThis.__hivemind_tuning__ ??= {};

// openclaw/src/setup-config.ts
import { existsSync, readFileSync, writeFileSync, renameSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
var HIVEMIND_TOOL_NAMES = ["hivemind_search", "hivemind_read", "hivemind_index"];
function getOpenclawConfigPath() {
  return join(homedir(), ".openclaw", "openclaw.json");
}
function isAllowlistCoveringHivemind(alsoAllow) {
  if (!Array.isArray(alsoAllow)) return false;
  for (const entry of alsoAllow) {
    if (typeof entry !== "string") continue;
    const normalized = entry.trim().toLowerCase();
    if (normalized === "hivemind") return true;
    if (normalized === "group:plugins") return true;
    if (HIVEMIND_TOOL_NAMES.includes(normalized)) return true;
  }
  return false;
}
function isPluginsAllowMissingHivemind(allow) {
  return Array.isArray(allow) && allow.length > 0 && !allow.includes("hivemind");
}
function ensureHivemindAllowlisted() {
  const configPath = getOpenclawConfigPath();
  if (!existsSync(configPath)) {
    return { status: "error", configPath, error: "openclaw config file not found" };
  }
  let parsed;
  try {
    const raw = readFileSync(configPath, "utf-8");
    parsed = JSON.parse(raw);
  } catch (e) {
    return { status: "error", configPath, error: `could not read/parse config: ${e instanceof Error ? e.message : String(e)}` };
  }
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
    return { status: "error", configPath, error: "openclaw config is not a JSON object" };
  }
  const plugins = parsed.plugins ?? {};
  const pluginsAllowRaw = plugins.allow;
  const tools = parsed.tools ?? {};
  const alsoAllowRaw = tools.alsoAllow;
  const pluginsAllowNeedsPatch = isPluginsAllowMissingHivemind(pluginsAllowRaw);
  const toolsAlsoAllowNeedsPatch = Array.isArray(alsoAllowRaw) && alsoAllowRaw.length > 0 && !isAllowlistCoveringHivemind(alsoAllowRaw);
  if (!pluginsAllowNeedsPatch && !toolsAlsoAllowNeedsPatch) {
    return { status: "already-set", configPath };
  }
  const updated = { ...parsed };
  if (pluginsAllowNeedsPatch) {
    updated.plugins = {
      ...plugins,
      // Cast safe — isPluginsAllowMissingHivemind guarantees Array.
      allow: [...pluginsAllowRaw, "hivemind"]
    };
  }
  if (toolsAlsoAllowNeedsPatch) {
    updated.tools = {
      ...tools,
      // Cast safe — the needs-patch check above guarantees Array.
      alsoAllow: [...alsoAllowRaw, "hivemind"]
    };
  }
  const backupPath = `${configPath}.bak-hivemind-${Date.now()}`;
  const tmpPath = `${configPath}.tmp-hivemind-${process.pid}`;
  try {
    writeFileSync(backupPath, readFileSync(configPath, "utf-8"));
    writeFileSync(tmpPath, JSON.stringify(updated, null, 2) + "\n");
    renameSync(tmpPath, configPath);
  } catch (e) {
    return { status: "error", configPath, error: `could not write config: ${e instanceof Error ? e.message : String(e)}` };
  }
  return {
    status: "added",
    configPath,
    backupPath,
    delta: {
      pluginsAllow: pluginsAllowNeedsPatch,
      toolsAlsoAllow: toolsAlsoAllowNeedsPatch
    }
  };
}
function toggleAutoUpdateConfig(setTo) {
  const configPath = getOpenclawConfigPath();
  if (!existsSync(configPath)) {
    return { status: "error", configPath, error: "openclaw config file not found" };
  }
  let parsed;
  try {
    parsed = JSON.parse(readFileSync(configPath, "utf-8"));
  } catch (e) {
    return { status: "error", configPath, error: `could not read/parse config: ${e instanceof Error ? e.message : String(e)}` };
  }
  const plugins = parsed.plugins ?? {};
  const entries = plugins.entries ?? {};
  const hivemindEntry = entries.hivemind ?? {};
  const pluginConfig = hivemindEntry.config ?? {};
  const current = pluginConfig.autoUpdate !== false;
  const newValue = typeof setTo === "boolean" ? setTo : !current;
  const updated = {
    ...parsed,
    plugins: {
      ...plugins,
      entries: {
        ...entries,
        hivemind: {
          ...hivemindEntry,
          config: { ...pluginConfig, autoUpdate: newValue }
        }
      }
    }
  };
  const backupPath = `${configPath}.bak-hivemind-${Date.now()}`;
  const tmpPath = `${configPath}.tmp-hivemind-${process.pid}`;
  try {
    writeFileSync(backupPath, readFileSync(configPath, "utf-8"));
    writeFileSync(tmpPath, JSON.stringify(updated, null, 2) + "\n");
    renameSync(tmpPath, configPath);
  } catch (e) {
    return { status: "error", configPath, error: `could not write config: ${e instanceof Error ? e.message : String(e)}` };
  }
  return { status: "updated", configPath, newValue };
}
function detectAllowlistMissing() {
  const configPath = getOpenclawConfigPath();
  if (!existsSync(configPath)) return false;
  try {
    const parsed = JSON.parse(readFileSync(configPath, "utf-8"));
    if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
    const plugins = parsed.plugins ?? {};
    const tools = parsed.tools ?? {};
    const alsoAllow = tools.alsoAllow;
    const toolsMissing = Array.isArray(alsoAllow) && alsoAllow.length > 0 && !isAllowlistCoveringHivemind(alsoAllow);
    return isPluginsAllowMissingHivemind(plugins.allow) || toolsMissing;
  } catch {
    return false;
  }
}
export {
  HIVEMIND_TOOL_NAMES,
  detectAllowlistMissing,
  ensureHivemindAllowlisted,
  getOpenclawConfigPath,
  isAllowlistCoveringHivemind,
  isPluginsAllowMissingHivemind,
  toggleAutoUpdateConfig
};
