import {
  withGatewayPreamble
} from "./chunk-YE2RMJY7.js";
import {
  resolveToolset
} from "./chunk-FX2AEKOV.js";
import {
  getConfig
} from "./chunk-2MAQ6JFL.js";
import {
  isAnthropicOAuthToken
} from "./chunk-J5Z5DSH4.js";

// src/backends/claude/args.ts
function buildClaudeArgs(input) {
  const cfg = getConfig();
  const policy = input.agent.permission_policy;
  const permissionMode = input.confirmationMode ? "default" : policy ? "default" : "bypassPermissions";
  const argv = [
    "-p",
    "--output-format",
    "stream-json",
    "--verbose",
    "--permission-mode",
    permissionMode
  ];
  const maxTurns = input.maxTurns ?? cfg.agentMaxTurns;
  if (maxTurns > 0) {
    argv.push("--max-turns", String(maxTurns));
  }
  if (input.claudeSessionId) {
    argv.push("--resume", input.claudeSessionId);
  }
  const tools = resolveToolset(input.agent.tools);
  let systemPrompt = withGatewayPreamble(input.agent.system, input.memoryStores);
  if (tools.customToolNames.size > 0) {
    const toolList = Array.from(tools.customToolNames).map((name) => `mcp__tool-bridge__${name}`).join(", ");
    systemPrompt += `

Your custom tools are: ${toolList}. Call them by these exact names \u2014 do not use ToolSearch to find them.`;
  }
  argv.push("--system-prompt", systemPrompt);
  if (input.agent.model) {
    argv.push("--model", input.agent.model.id);
  }
  const mcpToolNames = Array.from(tools.customToolNames).map(
    (name) => `mcp__tool-bridge__${name}`
  );
  const policyAllowed = policy?.always_allow ?? [];
  const allAllowed = [...tools.allowedTools, ...mcpToolNames, ...policyAllowed];
  if (allAllowed.length) {
    argv.push("--allowed-tools", allAllowed.join(","));
  }
  if (tools.disallowedTools.length) {
    argv.push("--disallowed-tools", tools.disallowedTools.join(","));
  }
  if (input.agent.model_config?.speed === "fast") {
    argv.push("--fast");
  }
  if (input.agent.mcp_servers && input.agent.mcp_servers.length > 0) {
    const mcpRecord = {};
    for (const s of input.agent.mcp_servers) {
      const { name, ...rest } = s;
      mcpRecord[name] = rest;
    }
    argv.push(
      "--mcp-config",
      JSON.stringify({ mcpServers: mcpRecord })
    );
  }
  return argv;
}
function buildClaudeAuthEnv() {
  const cfg = getConfig();
  const env = {};
  const token = cfg.claudeToken || cfg.anthropicApiKey;
  if (token) {
    if (isAnthropicOAuthToken(token)) {
      env.CLAUDE_CODE_OAUTH_TOKEN = token;
    } else {
      env.ANTHROPIC_API_KEY = token;
    }
  }
  return env;
}

export {
  buildClaudeArgs,
  buildClaudeAuthEnv
};
