import {
  createClaudeTranslator
} from "./chunk-4YC37DDW.js";
import {
  buildClaudeArgs,
  buildClaudeAuthEnv
} from "./chunk-H5YPGXEY.js";
import {
  PERMISSION_BRIDGE_DIR,
  PERMISSION_HOOK_SCRIPT_PATH,
  buildPermissionHooksConfig,
  generatePermissionHookScript
} from "./chunk-CY6AWCC6.js";
import {
  TOOL_BRIDGE_DIR,
  TOOL_BRIDGE_SCRIPT_PATH,
  TOOL_BRIDGE_TOOLS_PATH,
  buildBridgeMcpConfig,
  generateBridgeScript,
  toolsToJson
} from "./chunk-VRRGSQI7.js";
import {
  CLAUDE_WRAPPER_PATH,
  installClaudeWrapper
} from "./chunk-7AFOH6YL.js";
import {
  getConfig
} from "./chunk-2MAQ6JFL.js";

// src/backends/claude/index.ts
function buildTurn(input) {
  const { agent, backendSessionId, promptText, toolResults } = input;
  const argsBase = buildClaudeArgs({
    agent,
    claudeSessionId: backendSessionId,
    confirmationMode: agent.confirmation_mode,
    memoryStores: input.memoryStores
  });
  const env = buildClaudeAuthEnv();
  const customTools = agent.tools.filter((t) => t.type === "custom");
  const hasBridgeTools = customTools.length > 0 || agent.threads_enabled;
  if (hasBridgeTools || agent.mcp_servers && agent.mcp_servers.length > 0) {
    const mcpIdx = argsBase.indexOf("--mcp-config");
    let existingServers = {};
    if (mcpIdx >= 0 && mcpIdx + 1 < argsBase.length) {
      try {
        const existing = JSON.parse(argsBase[mcpIdx + 1]);
        existingServers = existing.mcpServers ?? {};
      } catch {
      }
      argsBase.splice(mcpIdx, 2);
    }
    const merged = hasBridgeTools ? buildBridgeMcpConfig(existingServers) : existingServers;
    argsBase.push("--mcp-config", JSON.stringify({ mcpServers: merged }));
  }
  if (toolResults.length > 0) {
    const args = [...argsBase, "--input-format", "stream-json"];
    const content = [];
    if (promptText) {
      content.push({ type: "text", text: promptText });
    }
    for (const r of toolResults) {
      content.push({
        type: "tool_result",
        tool_use_id: r.custom_tool_use_id,
        content: r.content
      });
    }
    const userFrame = JSON.stringify({
      type: "user",
      message: { role: "user", content }
    });
    return { argv: args, env, stdin: userFrame };
  }
  return { argv: argsBase, env, stdin: promptText };
}
function validateRuntime() {
  const cfg = getConfig();
  if (!cfg.anthropicApiKey && !cfg.claudeToken) {
    return null;
  }
  return null;
}
async function installToolBridge(sandboxName, customTools, provider) {
  if (customTools.length === 0) return;
  await provider.exec(sandboxName, ["mkdir", "-p", TOOL_BRIDGE_DIR]);
  await provider.exec(
    sandboxName,
    ["sh", "-c", `cat > "${TOOL_BRIDGE_SCRIPT_PATH}"`],
    { stdin: generateBridgeScript() }
  );
  await provider.exec(
    sandboxName,
    ["sh", "-c", `cat > "${TOOL_BRIDGE_TOOLS_PATH}"`],
    { stdin: toolsToJson(customTools) }
  );
  await provider.exec(sandboxName, ["chmod", "+x", TOOL_BRIDGE_SCRIPT_PATH]);
}
async function installPermissionHook(sandboxName, provider) {
  await provider.exec(sandboxName, ["mkdir", "-p", PERMISSION_BRIDGE_DIR]);
  await provider.exec(
    sandboxName,
    ["sh", "-c", `cat > ${PERMISSION_HOOK_SCRIPT_PATH}`],
    { stdin: generatePermissionHookScript() }
  );
  await provider.exec(sandboxName, ["chmod", "+x", PERMISSION_HOOK_SCRIPT_PATH]);
  const hooksConfig = buildPermissionHooksConfig();
  const homeResult = await provider.exec(sandboxName, ["sh", "-c", "echo $HOME"]);
  const homeDir = homeResult.stdout.replace(/[\x00-\x1f]/g, "").trim() || "/home/sprite";
  const settingsPath = `${homeDir}/.claude/settings.json`;
  let existingSettings = {};
  try {
    const result = await provider.exec(
      sandboxName,
      ["cat", settingsPath]
    );
    if (result.stdout.trim()) {
      existingSettings = JSON.parse(result.stdout);
    }
  } catch {
  }
  const merged = { ...existingSettings, ...hooksConfig };
  await provider.exec(
    sandboxName,
    ["sh", "-c", `mkdir -p "${homeDir}/.claude" && cat > "${settingsPath}"`],
    { stdin: JSON.stringify(merged, null, 2) }
  );
}
var claudeBackend = {
  name: "claude",
  wrapperPath: CLAUDE_WRAPPER_PATH,
  buildTurn,
  createTranslator: (opts) => createClaudeTranslator(opts),
  prepareOnSandbox: (name, provider) => installClaudeWrapper(name, provider),
  validateRuntime,
  // Firecracker / Cloud Run cold-start (~1.2s Node) exceeds claude's
  // default 5s MCP server connect timeout. 30s is a safe margin.
  mcpTimeoutMs: 3e4,
  // Claude Code's --input-format stream-json + tool-bridge sentinel
  // file support custom-tool re-entry via user.custom_tool_result.
  supportsCustomTools: true,
  // Claude Code auto-discovers skills from .claude/skills/ in $HOME.
  // installSkills also writes to .agents/skills/ for cross-engine
  // compatibility (handled in lifecycle.ts).
  extraSkillDirs: [".claude/skills"]
};

export {
  installToolBridge,
  installPermissionHook,
  claudeBackend
};
