/**
 * Config Command - CLI configuration management
 */
import chalk from 'chalk';
import inquirer from 'inquirer';
import * as fs from 'fs';
import * as path from 'path';
import { normalizePersonaMode } from '../utils/persona.js';
import { CH } from '../utils/logger.js';
export class ConfigCommand {
    config;
    logger;
    constructor(config, logger) {
        this.config = config;
        this.logger = logger;
    }
    async run(options) {
        if (options.reset) {
            await this.resetConfig();
            return;
        }
        if (options.set) {
            this.setConfig(options.set);
            return;
        }
        if (options.get) {
            this.getConfig(options.get);
            return;
        }
        if (options.list) {
            this.listConfig();
            return;
        }
        // Interactive mode
        await this.interactiveConfig();
    }
    async init(options = {}) {
        console.log();
        console.log(chalk.cyan(`${CH.hDouble.repeat(3)} Initialize Vigthoria in Project ${CH.hDouble.repeat(3)}`));
        console.log();
        const cwd = process.cwd();
        const configFile = path.join(cwd, '.vigthoria.json');
        const allowedModels = new Set(['code', 'code-35b', 'code-9b', 'balanced', 'balanced-4b']);
        const hasOverrides = Boolean(options.model ||
            options.ignorePatterns !== undefined ||
            options.autoApplyFixes !== undefined ||
            options.profile);
        const nonInteractive = Boolean(options.nonInteractive || options.yes || hasOverrides);
        if (fs.existsSync(configFile)) {
            if (nonInteractive) {
                if (!options.yes) {
                    this.logger.error('.vigthoria.json already exists. Re-run with --yes to overwrite in non-interactive mode.');
                    return;
                }
            }
            else {
                const { overwrite } = await inquirer.prompt([
                    {
                        type: 'confirm',
                        name: 'overwrite',
                        message: '.vigthoria.json already exists. Overwrite?',
                        default: false,
                    },
                ]);
                if (!overwrite) {
                    this.logger.info('Initialization cancelled');
                    return;
                }
            }
        }
        let settings;
        if (nonInteractive) {
            const profileDefaults = {
                safe: { defaultModel: 'balanced', autoApplyFixes: false },
                balanced: { defaultModel: 'code', autoApplyFixes: false },
                fast: { defaultModel: 'code-9b', autoApplyFixes: true },
            };
            const profile = options.profile && profileDefaults[options.profile] ? options.profile : 'balanced';
            const defaults = profileDefaults[profile];
            const model = options.model || defaults.defaultModel;
            if (!allowedModels.has(model)) {
                this.logger.error(`Invalid --model: ${model}`);
                this.logger.info('Allowed values: code, code-35b, code-9b, balanced, balanced-4b');
                return;
            }
            settings = {
                defaultModel: model,
                ignorePatterns: options.ignorePatterns || '',
                autoApplyFixes: options.autoApplyFixes !== undefined ? options.autoApplyFixes : defaults.autoApplyFixes,
            };
        }
        else {
            // Gather project settings interactively
            settings = await inquirer.prompt([
                {
                    type: 'list',
                    name: 'defaultModel',
                    message: 'Default AI model:',
                    choices: [
                        { name: '═══ Code Models ═══', disabled: true },
                        { name: 'Vigthoria v3 Code 35B - Flagship coding model', value: 'code' },
                        { name: 'Vigthoria v3 Code 35B - Explicit 35B selection', value: 'code-35b' },
                        { name: 'Vigthoria v3 Code 9B - Fast coding specialist', value: 'code-9b' },
                        { name: '═══ General Models ═══', disabled: true },
                        { name: 'Vigthoria Master 7.6B - Balanced general model', value: 'balanced' },
                        { name: 'Vigthoria v3 Balanced 4B - Efficient general purpose', value: 'balanced-4b' },
                    ],
                    default: 'code',
                },
                {
                    type: 'input',
                    name: 'ignorePatterns',
                    message: 'Additional ignore patterns (comma-separated):',
                    default: '',
                },
                {
                    type: 'confirm',
                    name: 'autoApplyFixes',
                    message: 'Auto-apply fixes without confirmation?',
                    default: false,
                },
            ]);
        }
        // Create project config
        const projectConfig = {
            defaultModel: settings.defaultModel,
            ignorePatterns: settings.ignorePatterns
                ? settings.ignorePatterns.split(',').map((p) => p.trim())
                : [],
            autoApplyFixes: settings.autoApplyFixes,
            createdAt: new Date().toISOString(),
        };
        fs.writeFileSync(configFile, JSON.stringify(projectConfig, null, 2));
        this.logger.success(`Created ${configFile}`);
        // Add to .gitignore if exists
        const gitignorePath = path.join(cwd, '.gitignore');
        if (fs.existsSync(gitignorePath)) {
            const gitignore = fs.readFileSync(gitignorePath, 'utf-8');
            if (!gitignore.includes('.vigthoria.json')) {
                fs.appendFileSync(gitignorePath, '\n# Vigthoria CLI\n.vigthoria.json\n');
                this.logger.info('Added .vigthoria.json to .gitignore');
            }
        }
        console.log();
        if (nonInteractive) {
            console.log(chalk.gray('Project initialized in non-interactive mode.'));
        }
        console.log(chalk.gray('Project initialized! Run vigthoria start for a beginner guide or vigthoria chat to begin.'));
        console.log();
    }
    setConfig(keyValue) {
        const [key, ...valueParts] = keyValue.split('=');
        const value = valueParts.join('=');
        if (!key || value === undefined) {
            this.logger.error('Invalid format. Use: vigthoria config --set key=value');
            return;
        }
        const configMap = {
            'model': (v) => this.config.set('preferences', { ...this.config.get('preferences'), defaultModel: v }),
            'theme': (v) => this.config.set('preferences', { ...this.config.get('preferences'), theme: v }),
            'autoApply': (v) => this.config.set('preferences', { ...this.config.get('preferences'), autoApplyFixes: v === 'true' }),
            'showDiffs': (v) => this.config.set('preferences', { ...this.config.get('preferences'), showDiffs: v === 'true' }),
            'maxTokens': (v) => this.config.set('preferences', { ...this.config.get('preferences'), maxTokens: parseInt(v, 10) }),
            'apiUrl': (v) => this.config.set('apiUrl', v),
            'modelsApiUrl': (v) => this.config.set('modelsApiUrl', v),
            'wsUrl': (v) => this.config.set('wsUrl', v),
            'selfHostedModelsApiUrl': (v) => this.config.set('selfHostedModelsApiUrl', v === 'null' || v === 'off' ? null : v),
            'persona': (v) => {
                const mode = normalizePersonaMode(v);
                if (!mode)
                    throw new Error('Invalid persona. Use: default or wiener_grant');
                this.config.set('persona', mode);
            },
        };
        if (configMap[key]) {
            configMap[key](value);
            this.logger.success(`Set ${key} = ${this.formatConfigValueForDisplay(key, value)}`);
        }
        else {
            this.logger.error(`Unknown config key: ${key}`);
            console.log(chalk.gray('Available keys: model, theme, autoApply, showDiffs, maxTokens, persona, apiUrl, modelsApiUrl, wsUrl, selfHostedModelsApiUrl'));
        }
    }
    formatConfigValueForDisplay(key, value) {
        if (key === 'apiUrl' || key === 'modelsApiUrl' || key === 'wsUrl' || key === 'selfHostedModelsApiUrl') {
            return this.redactConfigUrl(value);
        }
        return value;
    }
    redactConfigUrl(url) {
        const text = String(url || '').trim();
        if (!text)
            return text;
        try {
            const parsed = new URL(text);
            const host = parsed.hostname.toLowerCase();
            const isLocal = host === 'localhost' || host === '127.0.0.1';
            const isPrivate = /^10\./.test(host)
                || /^192\.168\./.test(host)
                || /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(host);
            if (isLocal || isPrivate) {
                return '[redacted-host]';
            }
            return text;
        }
        catch {
            return text.replace(/\b(?:localhost|127\.0\.0\.1)(?::\d+)?\b/gi, '[redacted-host]');
        }
    }
    getConfig(key) {
        const all = this.config.getAll();
        const flatConfig = {
            apiUrl: all.apiUrl,
            modelsApiUrl: all.modelsApiUrl,
            wsUrl: all.wsUrl,
            selfHostedModelsApiUrl: all.selfHostedModelsApiUrl,
            model: all.preferences.defaultModel,
            theme: all.preferences.theme,
            autoApply: all.preferences.autoApplyFixes,
            showDiffs: all.preferences.showDiffs,
            maxTokens: all.preferences.maxTokens,
            email: all.email,
            plan: all.subscription.plan,
            persona: all.persona,
        };
        if (key in flatConfig) {
            console.log(flatConfig[key]);
        }
        else {
            this.logger.error(`Unknown config key: ${key}`);
        }
    }
    listConfig() {
        const all = this.config.getAll();
        console.log();
        console.log(chalk.cyan('═══ Vigthoria CLI Configuration ═══'));
        console.log();
        console.log(chalk.white('API:'));
        console.log(chalk.gray('  URL: ') + chalk.cyan(this.redactConfigUrl(all.apiUrl)));
        console.log(chalk.gray('  Models API: ') + chalk.cyan(this.redactConfigUrl(all.modelsApiUrl)));
        console.log(chalk.gray('  WebSocket: ') + chalk.cyan(this.redactConfigUrl(all.wsUrl)));
        console.log(chalk.gray('  Vigthoria Model Endpoint: ') + chalk.cyan(all.selfHostedModelsApiUrl || 'default'));
        console.log();
        console.log(chalk.white('Preferences:'));
        console.log(chalk.gray('  Default Model: ') + chalk.cyan(all.preferences.defaultModel));
        console.log(chalk.gray('  Theme: ') + chalk.cyan(all.preferences.theme));
        console.log(chalk.gray('  Auto Apply Fixes: ') + chalk.cyan(all.preferences.autoApplyFixes));
        console.log(chalk.gray('  Show Diffs: ') + chalk.cyan(all.preferences.showDiffs));
        console.log(chalk.gray('  Max Tokens: ') + chalk.cyan(all.preferences.maxTokens));
        console.log(chalk.gray('  Persona: ') + chalk.cyan(all.persona));
        console.log();
        console.log(chalk.white('Project:'));
        console.log(chalk.gray('  Ignore Patterns: ') + chalk.gray(all.project.ignorePatterns.join(', ')));
        console.log();
        console.log(chalk.gray(`Config file: ${this.config.getConfigPath()}`));
        console.log();
    }
    async resetConfig() {
        const { confirm } = await inquirer.prompt([
            {
                type: 'confirm',
                name: 'confirm',
                message: 'Reset all settings to defaults? (This will not log you out)',
                default: false,
            },
        ]);
        if (confirm) {
            // Save auth before reset
            const authToken = this.config.get('authToken');
            const refreshToken = this.config.get('refreshToken');
            const userId = this.config.get('userId');
            const email = this.config.get('email');
            const subscription = this.config.get('subscription');
            this.config.reset();
            // Restore auth
            if (authToken) {
                this.config.set('authToken', authToken);
                this.config.set('refreshToken', refreshToken);
                this.config.set('userId', userId);
                this.config.set('email', email);
                this.config.set('subscription', subscription);
            }
            this.logger.success('Configuration reset to defaults');
        }
    }
    async interactiveConfig() {
        const current = this.config.getAll();
        console.log();
        console.log(chalk.cyan('═══ Configure Vigthoria CLI ═══'));
        console.log();
        const settings = await inquirer.prompt([
            {
                type: 'list',
                name: 'defaultModel',
                message: 'Default AI model:',
                choices: [
                    { name: 'Vigthoria v3 Code 35B', value: 'code' },
                    { name: 'Vigthoria v3 Code 9B', value: 'code-9b' },
                    { name: 'Vigthoria Master 7.6B', value: 'balanced' },
                    { name: 'Vigthoria v3 Balanced 4B', value: 'balanced-4b' },
                ],
                default: current.preferences.defaultModel,
            },
            {
                type: 'list',
                name: 'theme',
                message: 'Color theme:',
                choices: ['dark', 'light'],
                default: current.preferences.theme,
            },
            {
                type: 'confirm',
                name: 'autoApplyFixes',
                message: 'Auto-apply fixes without confirmation?',
                default: current.preferences.autoApplyFixes,
            },
            {
                type: 'confirm',
                name: 'showDiffs',
                message: 'Show diffs before applying changes?',
                default: current.preferences.showDiffs,
            },
            {
                type: 'number',
                name: 'maxTokens',
                message: 'Maximum tokens per response:',
                default: current.preferences.maxTokens,
            },
        ]);
        this.config.set('preferences', {
            ...current.preferences,
            ...settings,
        });
        this.logger.success('Configuration saved');
        console.log();
    }
}
