import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { homedir } from "node:os";
import { execSync } from "node:child_process";
import { parse as parseToml, stringify as stringifyToml } from "@iarna/toml";
import { mergeBlock, removeBlock, readAsset } from "./utils.js";
const TOML_TABLE_PATH = ["mcp_servers", "wigolo"];
function codexDir() {
  return join(homedir(), ".codex");
}
function detect() {
  if (existsSync(codexDir())) return true;
  try {
    execSync("which codex", { stdio: ["pipe", "pipe", "pipe"] });
    return true;
  } catch {
    return false;
  }
}
function mergeTomlEntry(configPath, tablePath, entry) {
  mkdirSync(dirname(configPath), { recursive: true });
  let root = {};
  if (existsSync(configPath)) {
    try {
      const raw = readFileSync(configPath, "utf-8");
      if (raw.trim().length > 0) {
        root = parseToml(raw);
      }
    } catch {
      root = {};
    }
  }
  let obj = root;
  for (let i = 0; i < tablePath.length - 1; i++) {
    const k = tablePath[i];
    if (typeof obj[k] !== "object" || obj[k] === null) {
      obj[k] = {};
    }
    obj = obj[k];
  }
  obj[tablePath[tablePath.length - 1]] = entry;
  writeFileSync(configPath, stringifyToml(root));
}
function removeTomlEntry(configPath, tablePath) {
  if (!existsSync(configPath)) return;
  let root;
  try {
    root = parseToml(readFileSync(configPath, "utf-8"));
  } catch {
    return;
  }
  let obj = root;
  for (let i = 0; i < tablePath.length - 1; i++) {
    const k = tablePath[i];
    if (typeof obj[k] !== "object" || obj[k] === null) return;
    obj = obj[k];
  }
  delete obj[tablePath[tablePath.length - 1]];
  writeFileSync(configPath, stringifyToml(root));
}
async function installMcp(cmd) {
  const dir = codexDir();
  mkdirSync(dir, { recursive: true });
  mergeTomlEntry(join(dir, "config.toml"), TOML_TABLE_PATH, {
    command: cmd.command,
    args: cmd.args
  });
}
async function installInstructions() {
  const block = readAsset("blocks/codex/AGENTS.md.block");
  const target = join(process.cwd(), "AGENTS.md");
  mergeBlock(target, block);
}
async function uninstall() {
  const removed = [];
  const configPath = join(codexDir(), "config.toml");
  if (existsSync(configPath)) {
    removeTomlEntry(configPath, TOML_TABLE_PATH);
    removed.push("~/.codex/config.toml (wigolo mcp_servers entry)");
  }
  const agentsMd = join(process.cwd(), "AGENTS.md");
  if (existsSync(agentsMd) && removeBlock(agentsMd)) {
    removed.push("AGENTS.md block");
  }
  return { removed };
}
const codexHandler = {
  id: "codex",
  displayName: "Codex (OpenAI CLI)",
  supportsSkills: false,
  supportsCommands: false,
  detect,
  installMcp,
  installInstructions,
  uninstall
};
export {
  codexHandler
};
//# sourceMappingURL=codex.js.map