/**
 * Interactive V3/V4 agent + V4 provider picker, styled to match the rest of
 * the Vigthoria CLI's menus (see agent-session-menu.ts). This is invoked as a
 * subprocess (with inherited stdio, so it keeps full TTY/inquirer rendering)
 * by the V4 Operating Agent's Python launcher (cli_menu.py) instead of that
 * project rendering its own boxed prompt_toolkit dialog, which looked
 * inconsistent with the CLI's visual design.
 *
 * The result is written as JSON to --out-file rather than printed to stdout,
 * so stdout can stay fully interactive (a piped stdout would make inquirer
 * fall back to non-interactive/plain rendering).
 */
import * as fs from 'fs';
import chalk from 'chalk';
import inquirer from 'inquirer';
function isCancelError(error) {
    const name = error instanceof Error ? error.name : '';
    return name === 'ExitPromptError' || name === 'ERR_CLOSED';
}
function writeResult(outFile, result) {
    fs.writeFileSync(outFile, JSON.stringify(result), 'utf8');
}
export async function runV4Menu(options) {
    const defaultAgent = options.defaultAgent === 'v4' ? 'v4' : 'v3';
    const defaultProvider = options.defaultProvider === 'v3_local' || options.defaultProvider === 'byok'
        ? options.defaultProvider
        : 'cloud';
    console.log();
    console.log(chalk.cyan('═══ Vigthoria Agent Launcher ═══'));
    console.log(chalk.gray('Choose which agent runtime to start.'));
    console.log();
    try {
        const { agent } = await inquirer.prompt([
            {
                type: 'list',
                name: 'agent',
                message: 'Select runtime',
                default: defaultAgent,
                choices: [
                    { name: 'V3 Code Agent', value: 'v3' },
                    { name: 'V4 Operating Agent', value: 'v4' },
                ],
            },
        ]);
        if (agent === 'v3') {
            console.log();
            console.log(chalk.cyan('── Session ready ──'));
            console.log(chalk.gray('Runtime: V3 Code Agent'));
            console.log();
            writeResult(options.outFile, { agent: 'v3' });
            return;
        }
        const { provider } = await inquirer.prompt([
            {
                type: 'list',
                name: 'provider',
                message: 'Select V4 backend',
                default: defaultProvider,
                choices: [
                    { name: 'Vigthoria Cloud (Gateway + Session Wallet Token)', value: 'cloud' },
                    { name: 'Vigthoria V3 Local (Blackwell 35B Direct)', value: 'v3_local' },
                    { name: 'Bring Your Own Key (API Key + Base URL + Model)', value: 'byok' },
                ],
            },
        ]);
        if (provider !== 'byok') {
            console.log();
            console.log(chalk.cyan('── Session ready ──'));
            console.log(chalk.gray(`Runtime: V4 Operating Agent (${provider === 'cloud' ? 'Vigthoria Cloud' : 'Vigthoria V3 Local'})`));
            console.log();
            writeResult(options.outFile, { agent: 'v4', provider });
            return;
        }
        const existingApiKey = String(options.byokApiKey || '').trim();
        const existingBaseUrl = String(options.byokBaseUrl || '').trim();
        const existingModel = String(options.byokModel || '').trim();
        const missing = !existingApiKey || !existingBaseUrl || !existingModel;
        const questions = [];
        if (!existingApiKey) {
            questions.push({
                type: 'password',
                name: 'apiKey',
                message: 'BYOK API key:',
                mask: '*',
                validate: (value) => (String(value || '').trim() ? true : 'API key is required.'),
            });
        }
        if (!existingBaseUrl) {
            questions.push({
                type: 'input',
                name: 'baseUrl',
                message: 'BYOK base URL:',
                validate: (value) => (String(value || '').trim() ? true : 'Base URL is required.'),
            });
        }
        if (!existingModel) {
            questions.push({
                type: 'input',
                name: 'model',
                message: 'BYOK default model:',
                validate: (value) => (String(value || '').trim() ? true : 'Model is required.'),
            });
        }
        const answers = questions.length > 0 ? await inquirer.prompt(questions) : {};
        const apiKey = String(answers.apiKey || existingApiKey).trim();
        const baseUrl = String(answers.baseUrl || existingBaseUrl).trim();
        const model = String(answers.model || existingModel).trim();
        let save = false;
        if (missing) {
            const { saveLocally } = await inquirer.prompt([
                {
                    type: 'confirm',
                    name: 'saveLocally',
                    message: 'Store BYOK values locally in ~/.config/vigthoria/config.yaml?',
                    default: true,
                },
            ]);
            save = saveLocally;
        }
        console.log();
        console.log(chalk.cyan('── Session ready ──'));
        console.log(chalk.gray('Runtime: V4 Operating Agent (Bring Your Own Key)'));
        console.log();
        writeResult(options.outFile, { agent: 'v4', provider: 'byok', apiKey, baseUrl, model, save });
    }
    catch (error) {
        if (isCancelError(error)) {
            console.log();
            console.log(chalk.yellow('Cancelled.'));
            writeResult(options.outFile, { cancelled: true });
            process.exitCode = 130;
            return;
        }
        throw error;
    }
}
