'use strict';

/**
 * Strip env-injected Anthropic auth before spawning a child process.
 *
 * Two passes:
 *   1. Always: when a real ANTHROPIC_API_KEY exists alongside the
 *      placeholder AUTH_TOKEN `sk-ant-api03-unused`, drop the placeholder
 *      and its companion gateway vars. This was the original CTM
 *      behavior — keeps spawned `claude` from emitting "auth conflict"
 *      warnings or routing to a private gateway the user may not have
 *      VPN'd into.
 *   2. When `cmd` is the `claude` CLI: drop ALL env-injected Anthropic
 *      auth so Claude Code falls back to its keychain `/login` state.
 *      CTM's process env often inherits routing tokens from Wall-E's
 *      OAuth-proxy strategy or shell rc; when those rotate or expire,
 *      Claude Code surfaces the synthetic 401 "Invalid API key · Fix
 *      external API key" because the env-source key took precedence
 *      over the keychain. Letting Claude Code own its own auth is the
 *      correct default — it matches what users see when they run
 *      `claude` from a fresh terminal.
 *
 *      Opt-out: set CTM_KEEP_ANTHROPIC_ENV_FOR_CLAUDE=1 (e.g. for
 *      corporate users running through a custom gateway who DO want
 *      every spawned session to inherit those env vars).
 *
 * Mutates `env` in place and returns it for chaining.
 */
function sanitizeAnthropicAuth(env, cmd) {
  if (env.ANTHROPIC_API_KEY && env.ANTHROPIC_AUTH_TOKEN === 'sk-ant-api03-unused') {
    delete env.ANTHROPIC_AUTH_TOKEN;
    delete env.ANTHROPIC_BASE_URL;
    delete env.ANTHROPIC_CUSTOM_HEADERS_B64;
  }
  if (typeof cmd === 'string' &&
      /(^|\/)claude($|\s)/.test(cmd) &&
      !process.env.CTM_KEEP_ANTHROPIC_ENV_FOR_CLAUDE) {
    delete env.ANTHROPIC_API_KEY;
    delete env.ANTHROPIC_AUTH_TOKEN;
    delete env.ANTHROPIC_BASE_URL;
    delete env.ANTHROPIC_CUSTOM_HEADERS_B64;
  }
  return env;
}

module.exports = { sanitizeAnthropicAuth };
