"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleProxyCommand = exports.findPositionalArg = void 0;
const env_command_1 = require("./env-command");
const config_manager_1 = require("../utils/config-manager");
const helpers_1 = require("../utils/helpers");
const ui_1 = require("../utils/ui");
const proxy_1 = require("../proxy");
const config_loader_facade_1 = require("../config/config-loader-facade");
function parseOptionValue(args, key) {
    const exactIndex = args.findIndex((arg) => arg === key);
    if (exactIndex !== -1 && args[exactIndex + 1]) {
        return args[exactIndex + 1];
    }
    const prefix = `${key}=`;
    const withEquals = args.find((arg) => arg.startsWith(prefix));
    return withEquals ? withEquals.slice(prefix.length) : undefined;
}
function hasHelpFlag(args) {
    return args.includes('--help') || args.includes('-h');
}
function findPositionalArg(args, optionsWithValues = [], flagOptions = []) {
    for (let i = 0; i < args.length; i += 1) {
        const arg = args[i];
        if (arg === '--') {
            return i + 1 < args.length ? args[i + 1] : undefined;
        }
        if (arg.startsWith('-')) {
            if (flagOptions.includes(arg)) {
                continue;
            }
            if (optionsWithValues.includes(arg)) {
                i += 1;
            }
            continue;
        }
        return arg;
    }
    return undefined;
}
exports.findPositionalArg = findPositionalArg;
function showHelp() {
    console.log('OpenAI-Compatible Proxy');
    console.log('');
    console.log('Usage: ccs proxy <start|stop|status|activate> [profile] [options]');
    console.log('');
    console.log('Commands:');
    console.log('  start <profile>   Start the local proxy for an OpenAI-compatible settings profile');
    console.log('  stop [profile]    Stop the running proxy (or all proxies when omitted)');
    console.log('  status [profile]  Show daemon status');
    console.log('  activate [profile] Print shell exports for the running proxy');
    console.log('');
    console.log('Options:');
    console.log('  --port <n>        Pin an exact local proxy port for this launch');
    console.log('  --host <addr>     Bind the proxy server to a specific host (default: 127.0.0.1)');
    console.log('  --shell <name>    activate only: auto|bash|zsh|fish|powershell');
    console.log('  --fish            activate only: shorthand for --shell fish');
    console.log('  --insecure        Disable upstream TLS verification');
    console.log('');
    console.log('Examples:');
    console.log('  ccs proxy start hf');
    console.log('  eval "$(ccs proxy activate)"');
    console.log('  ccs proxy activate --fish');
    console.log('  ccs proxy status');
    console.log('  ccs proxy stop');
    console.log('');
    return 0;
}
function resolveProfile(profileName) {
    const settingsPath = (0, helpers_1.expandPath)((0, config_manager_1.getSettingsPath)(profileName));
    const settings = (0, config_loader_facade_1.loadSettings)(settingsPath);
    const profile = (0, proxy_1.resolveOpenAICompatProfileConfig)(profileName, settingsPath, settings.env || {});
    if (!profile) {
        throw new Error(`Profile "${profileName}" is not configured for an OpenAI-compatible endpoint`);
    }
    return profile;
}
async function handleStart(args) {
    if (hasHelpFlag(args)) {
        return showHelp();
    }
    const profileName = findPositionalArg(args, ['--port', '--host'], ['--insecure']);
    if (!profileName) {
        console.error((0, ui_1.fail)('Usage: ccs proxy start <profile> [--port <n>] [--host <addr>] [--insecure]'));
        return 1;
    }
    const portValue = parseOptionValue(args, '--port');
    const host = parseOptionValue(args, '--host');
    const parsedPort = portValue ? Number(portValue) : undefined;
    if (portValue &&
        (parsedPort === undefined ||
            !/^\d+$/.test(portValue) ||
            !Number.isInteger(parsedPort) ||
            parsedPort < 1 ||
            parsedPort > 65535)) {
        console.error((0, ui_1.fail)(`Invalid port: ${portValue}`));
        return 1;
    }
    const port = parsedPort;
    let profile;
    try {
        profile = resolveProfile(profileName);
    }
    catch (error) {
        console.error((0, ui_1.fail)(error.message));
        return 1;
    }
    const result = await (0, proxy_1.startOpenAICompatProxy)(profile, {
        ...(port ? { port } : {}),
        ...(host ? { host } : {}),
        insecure: args.includes('--insecure'),
    });
    if (!result.success) {
        console.error((0, ui_1.fail)(result.error || 'Failed to start proxy'));
        return 1;
    }
    console.log(result.alreadyRunning
        ? (0, ui_1.info)(`Proxy already running on port ${result.port}`)
        : (0, ui_1.ok)(`Proxy started on port ${result.port}`));
    return 0;
}
async function handleStatus(args = []) {
    if (hasHelpFlag(args)) {
        return showHelp();
    }
    const profileName = findPositionalArg(args);
    const printStatus = (status) => {
        console.log(status.running
            ? (0, ui_1.ok)(`Proxy running on port ${status.port ?? 'unknown'}`)
            : (0, ui_1.info)(`Proxy is not running${status.port ? ` (last known port ${status.port})` : ''}`));
        if (status.host && status.port) {
            console.log(`  Host: ${status.host}`);
            console.log(`  Local URL: http://${status.host}:${status.port}`);
        }
        if (status.profileName) {
            console.log(`  Profile: ${status.profileName}`);
        }
        if (status.baseUrl) {
            console.log(`  Base URL: ${status.baseUrl}`);
        }
        if (status.model) {
            console.log(`  Model: ${status.model}`);
        }
        if (status.pid) {
            console.log(`  PID: ${status.pid}`);
        }
    };
    if (profileName) {
        const status = await (0, proxy_1.getOpenAICompatProxyStatus)(profileName);
        if (!status.running && !status.profileName) {
            console.log((0, ui_1.info)('Proxy is not running'));
            return 0;
        }
        printStatus(status);
        return 0;
    }
    const status = await (0, proxy_1.getOpenAICompatProxyStatus)();
    if (!status.running && !status.profileName) {
        console.log((0, ui_1.info)('Proxy is not running'));
        return 0;
    }
    if (status.running && !status.profileName) {
        const running = (await (0, proxy_1.listOpenAICompatProxyStatuses)()).filter((entry) => entry.running);
        for (const entry of running) {
            printStatus(entry);
        }
        return 0;
    }
    printStatus(status);
    return 0;
}
async function handleActivate(args) {
    if (hasHelpFlag(args)) {
        return showHelp();
    }
    const profileName = findPositionalArg(args, ['--shell']);
    if (!profileName) {
        const running = (await (0, proxy_1.listOpenAICompatProxyStatuses)()).filter((entry) => entry.running);
        if (running.length > 1) {
            console.error((0, ui_1.fail)('Multiple proxies are running. Specify a profile: ccs proxy activate <profile>'));
            return 1;
        }
    }
    const status = await (0, proxy_1.getOpenAICompatProxyStatus)(profileName);
    if (!status.running || !status.profileName || !status.port || !status.authToken) {
        console.error((0, ui_1.fail)('Proxy is not running. Start it with: ccs proxy start <profile>'));
        return 1;
    }
    const shell = (0, env_command_1.detectShell)(args.includes('--fish') ? 'fish' : parseOptionValue(args, '--shell'));
    let profile;
    try {
        profile = resolveProfile(status.profileName);
    }
    catch (error) {
        console.error((0, ui_1.fail)(error.message));
        return 1;
    }
    const env = (0, proxy_1.buildOpenAICompatProxyEnv)(profile, status.port, status.authToken, undefined, status.host || '127.0.0.1');
    Object.entries(env).forEach(([key, value]) => {
        console.log((0, env_command_1.formatExportLine)(shell, key, value));
    });
    return 0;
}
async function handleProxyCommand(args) {
    const subcommand = args[0];
    switch (subcommand) {
        case undefined:
        case 'help':
        case '--help':
        case '-h':
            return showHelp();
        case 'start':
            return handleStart(args.slice(1));
        case 'stop': {
            if (hasHelpFlag(args.slice(1))) {
                return showHelp();
            }
            const profileName = args[1] && !args[1].startsWith('-') ? args[1] : undefined;
            const result = await (0, proxy_1.stopOpenAICompatProxy)(profileName);
            if (!result.success) {
                console.error((0, ui_1.fail)(result.error || 'Failed to stop proxy'));
                return 1;
            }
            console.log((0, ui_1.ok)(profileName ? `Proxy stopped for profile ${profileName}` : 'Proxy stopped'));
            return 0;
        }
        case 'status':
            return handleStatus(args.slice(1));
        case 'activate':
            return handleActivate(args.slice(1));
        default:
            console.error((0, ui_1.fail)(`Unknown proxy subcommand: ${subcommand}`));
            return 1;
    }
}
exports.handleProxyCommand = handleProxyCommand;
//# sourceMappingURL=proxy-command.js.map