/**
 * Interactive agent/operator session setup menu (Node inquirer — CLI equivalent of InquirerPy).
 */
import chalk from 'chalk';
import inquirer from 'inquirer';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
function terminalColumns() {
    const raw = Number(process.stdout.columns || 80);
    return Number.isFinite(raw) && raw > 0 ? raw : 80;
}
function fitLine(text, reserve = 0) {
    const width = Math.max(24, terminalColumns() - reserve);
    const clean = String(text || '').replace(/\s+/g, ' ').trim();
    return clean.length > width ? `${clean.slice(0, Math.max(1, width - 1))}…` : clean;
}
function validateExistingDirectory(input) {
    const trimmed = String(input || '').trim().replace(/^['"]|['"]$/g, '');
    if (!trimmed) {
        return 'Path is required.';
    }
    const resolved = path.resolve(trimmed);
    try {
        if (!fs.existsSync(resolved)) {
            return `Directory does not exist: ${resolved}`;
        }
        if (!fs.statSync(resolved).isDirectory()) {
            return `Not a directory: ${resolved}`;
        }
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return `Cannot access path: ${message}`;
    }
    return true;
}
export function shouldShowAgentSessionMenu(options = {}) {
    if (options.prompt) {
        return false;
    }
    if (options.json) {
        return false;
    }
    if (options.projectProvided) {
        return false;
    }
    if (/^(1|true|yes)$/i.test(String(process.env.VIGTHORIA_NO_SESSION_MENU || ''))) {
        return false;
    }
    return Boolean(process.stdout.isTTY && process.stdin.isTTY);
}
async function promptSessionSettings(session) {
    const settings = await inquirer.prompt([
        {
            type: 'confirm',
            name: 'debugMode',
            message: 'Enable debug mode (verbose logging)?',
            default: session.debugMode,
        },
        {
            type: 'confirm',
            name: 'autoSave',
            message: 'Auto-save session on exit?',
            default: session.autoSave,
        },
        {
            type: 'confirm',
            name: 'autoApprove',
            message: 'Auto-approve tool actions (dangerous)?',
            default: session.autoApprove,
        },
    ]);
    Object.assign(session, settings);
}
async function confirmSettingsStep() {
    const { configureSettings } = await inquirer.prompt([
        {
            type: 'confirm',
            name: 'configureSettings',
            message: 'Configure debug, auto-save and auto-approve now?',
            default: false,
        },
    ]);
    return configureSettings;
}
export async function runAgentSessionMenu(defaults = {}) {
    const session = {
        workspacePath: path.resolve(String(defaults.workspacePath || process.cwd())),
        debugMode: defaults.debugMode === true,
        autoApprove: defaults.autoApprove === true,
        autoSave: defaults.autoSave !== false,
    };
    console.log();
    console.log(chalk.cyan('═══ Agent Session Setup ═══'));
    console.log(chalk.gray(fitLine(`Workspace: ${session.workspacePath}`)));
    console.log(chalk.gray(fitLine(`Debug: ${session.debugMode ? 'on' : 'off'} | Auto-approve: ${session.autoApprove ? 'on' : 'off'} | Auto-save: ${session.autoSave ? 'on' : 'off'}`)));
    console.log();
    const { action } = await inquirer.prompt([
        {
            type: 'list',
            name: 'action',
            message: 'Session',
            choices: [
                { name: 'Start now', value: 'start' },
                { name: 'Set workspace', value: 'set-workspace' },
                { name: 'Create workspace', value: 'create-workspace' },
                { name: 'Settings', value: 'settings' },
            ],
        },
    ]);
    if (action === 'set-workspace') {
        const { workspacePath } = await inquirer.prompt([
            {
                type: 'input',
                name: 'workspacePath',
                message: 'Workspace directory path:',
                default: session.workspacePath,
                validate: validateExistingDirectory,
            },
        ]);
        session.workspacePath = path.resolve(workspacePath);
        if (await confirmSettingsStep()) {
            await promptSessionSettings(session);
        }
    }
    else if (action === 'create-workspace') {
        const { basePath, folderName } = await inquirer.prompt([
            {
                type: 'input',
                name: 'basePath',
                message: 'Base directory:',
                default: os.homedir(),
                validate: validateExistingDirectory,
            },
            {
                type: 'input',
                name: 'folderName',
                message: 'New folder name:',
                validate: (value) => {
                    const trimmed = String(value || '').trim();
                    if (!trimmed) {
                        return 'Folder name is required.';
                    }
                    if (/[<>:"|?*\x00]/.test(trimmed)) {
                        return 'Folder name contains invalid characters.';
                    }
                    return true;
                },
            },
        ]);
        const target = path.join(path.resolve(basePath), String(folderName).trim());
        fs.mkdirSync(target, { recursive: true });
        session.workspacePath = target;
        console.log(chalk.green(`Created workspace: ${target}`));
        if (await confirmSettingsStep()) {
            await promptSessionSettings(session);
        }
    }
    else if (action === 'settings') {
        await promptSessionSettings(session);
    }
    console.log();
    console.log(chalk.cyan('── Session ready ──'));
    console.log(chalk.gray(fitLine(`Workspace: ${session.workspacePath}`)));
    console.log(chalk.gray(fitLine(`Debug: ${session.debugMode ? 'on' : 'off'} | Auto-approve: ${session.autoApprove ? 'on' : 'off'} | Auto-save: ${session.autoSave ? 'on' : 'off'}`)));
    console.log();
    return session;
}
