"use strict";
/**
 * Claude Adapter
 *
 * TargetAdapter implementation for Claude Code CLI.
 * Wraps existing detection, spawning, and execution logic.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClaudeAdapter = void 0;
const child_process_1 = require("child_process");
const claude_detector_1 = require("../utils/claude-detector");
const shell_executor_1 = require("../utils/shell-executor");
const error_manager_1 = require("../utils/error-manager");
const websearch_manager_1 = require("../utils/websearch-manager");
const browser_1 = require("../utils/browser");
const signal_forwarder_1 = require("../utils/signal-forwarder");
const errors_1 = require("../errors");
const logging_1 = require("../services/logging");
const adapterLogger = (0, logging_1.createLogger)('targets:claude');
class ClaudeAdapter {
    constructor() {
        this.type = 'claude';
        this.displayName = 'Claude Code';
    }
    detectBinary() {
        const info = (0, claude_detector_1.getClaudeCliInfo)();
        if (!info)
            return null;
        return { path: info.path, needsShell: info.needsShell };
    }
    /**
     * Claude uses env vars for credential delivery — no config file writes needed.
     */
    async prepareCredentials(_creds) {
        // No-op: Claude receives credentials via environment variables
    }
    buildArgs(_profile, userArgs, options) {
        return options?.creds?.browserRuntimeEnv ? (0, browser_1.appendBrowserToolArgs)(userArgs) : userArgs;
    }
    buildEnv(creds, profileType) {
        const webSearchEnv = (0, websearch_manager_1.getWebSearchHookEnv)();
        // For account/default profiles, strip ANTHROPIC_* from parent env to prevent
        // stale proxy config from interfering with native Claude API routing.
        const baseEnv = profileType === 'account' || profileType === 'default'
            ? (0, shell_executor_1.stripAnthropicEnv)(process.env)
            : process.env;
        const env = { ...(0, shell_executor_1.stripBrowserEnv)(baseEnv), ...webSearchEnv };
        if (creds.envVars) {
            Object.assign(env, (0, shell_executor_1.stripBrowserEnv)(creds.envVars));
        }
        if (creds.browserRuntimeEnv) {
            Object.assign(env, creds.browserRuntimeEnv);
        }
        if (creds.baseUrl)
            env['ANTHROPIC_BASE_URL'] = creds.baseUrl;
        if (creds.apiKey)
            env['ANTHROPIC_AUTH_TOKEN'] = creds.apiKey;
        if (creds.model)
            env['ANTHROPIC_MODEL'] = creds.model;
        return (0, shell_executor_1.stripClaudeCodeEnv)(env);
    }
    exec(args, env, _options) {
        const exitWithCleanup = (code) => {
            try {
                (0, errors_1.runCleanup)();
            }
            catch {
                // Cleanup should be best-effort on launch errors.
            }
            process.exit(code);
        };
        const claudeCli = (0, claude_detector_1.detectClaudeCli)();
        if (!claudeCli) {
            void error_manager_1.ErrorManager.showClaudeNotFound();
            return exitWithCleanup(1);
        }
        const isWindows = process.platform === 'win32';
        const isPowerShellScript = isWindows && /\.ps1$/i.test(claudeCli);
        const needsShell = isWindows && /\.(cmd|bat)$/i.test(claudeCli);
        const spawnStartedAt = Date.now();
        adapterLogger.stage('dispatch', 'target.spawn', 'Spawning Claude CLI child process', {
            target: 'claude',
            claudeCli,
            argCount: args.length,
        });
        let child;
        if (isPowerShellScript) {
            child = (0, child_process_1.spawn)('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', claudeCli, ...args], {
                stdio: 'inherit',
                windowsHide: true,
                env,
            });
        }
        else if (needsShell) {
            const cmdString = [claudeCli, ...args].map(shell_executor_1.escapeShellArg).join(' ');
            child = (0, child_process_1.spawn)(cmdString, {
                stdio: 'inherit',
                windowsHide: true,
                shell: (0, shell_executor_1.getWindowsEscapedCommandShell)(),
                env,
            });
        }
        else {
            child = (0, child_process_1.spawn)(claudeCli, args, {
                stdio: 'inherit',
                windowsHide: true,
                env,
            });
        }
        child.on('exit', (code, signal) => {
            adapterLogger.stage('respond', 'target.exit', 'Claude CLI child process exited', { target: 'claude', exitCode: code, signal }, { latencyMs: Date.now() - spawnStartedAt });
        });
        (0, signal_forwarder_1.wireChildProcessSignals)(child, async (err) => {
            if (err.code === 'EACCES') {
                console.error(`[X] Claude CLI is not executable: ${claudeCli}`);
                console.error('    Check file permissions and executable bit.');
            }
            else if (err.code === 'ENOENT') {
                if (isPowerShellScript) {
                    console.error('[X] PowerShell executable not found (required for .ps1 wrapper launch).');
                    console.error('    Ensure powershell.exe is available in PATH.');
                }
                else if (needsShell) {
                    console.error('[X] Windows command shell not found for Claude wrapper launch.');
                    console.error('    Ensure cmd.exe is available and accessible.');
                }
                else {
                    await error_manager_1.ErrorManager.showClaudeNotFound();
                }
            }
            else {
                console.error(`[X] Failed to start Claude CLI (${claudeCli}): ${err.message}`);
            }
            return exitWithCleanup(1);
        });
    }
    /**
     * Claude supports all CCS profile types.
     */
    supportsProfileType(_profileType) {
        return true;
    }
}
exports.ClaudeAdapter = ClaudeAdapter;
//# sourceMappingURL=claude-adapter.js.map