#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const safeLogger_1 = require("../utils/safeLogger");
(0, safeLogger_1.initSafeLogger)();
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const paths_1 = require("../config/paths");
const server_1 = require("./server");
const setup_1 = require("./setup");
const state_1 = require("../utils/state");
const picocolors_1 = __importDefault(require("picocolors"));
const parser_1 = require("../config/parser");
async function main() {
    // 1. Determine configuration directory
    const appDir = (0, paths_1.getAppDir)();
    const isGlobalMode = appDir !== process.cwd();
    console.log(`================================`);
    console.log(`🤖 Nyxora CLI Agent Booting Up...`);
    console.log(`📂 Config Directory: ${appDir}`);
    console.log(`================================`);
    // Check for explicit wizard command
    if (process.argv.includes('setup') || process.argv.includes('--wizard')) {
        await (0, setup_1.runSetupWizard)();
        process.exit(0);
    }
    // Check for memory clear command
    if (process.argv.includes('clear')) {
        if (process.argv.includes('--force') || process.argv.includes('-y')) {
            const { Logger } = require('../memory/logger');
            const logger = new Logger();
            logger.clear();
            console.log(picocolors_1.default.green('✅ Memory cleared successfully.'));
            process.exit(0);
        }
        else {
            console.log(picocolors_1.default.yellow('⚠️ Warning: This will wipe all AI memory. Run "nyxora clear --force" to confirm.'));
            process.exit(1);
        }
    }
    // Check for set-key shortcut
    if (process.argv.includes('set-key')) {
        const setKeyIndex = process.argv.indexOf('set-key');
        const provider = process.argv[setKeyIndex + 1];
        const key = process.argv[setKeyIndex + 2];
        if (!provider || !key) {
            console.error(picocolors_1.default.red('Usage: nyxora set-key <provider> <api_key>'));
            console.error(picocolors_1.default.gray('Example: nyxora set-key groq gsk_xxx'));
            console.error(picocolors_1.default.gray('Providers: openai, gemini, openrouter, groq, mistral, xai, deepseek, tavily, brave'));
            process.exit(1);
        }
        const keyMap = {
            'openai': 'openai_key',
            'gemini': 'gemini_key',
            'openrouter': 'openrouter_key',
            'groq': 'groq_key',
            'mistral': 'mistral_key',
            'xai': 'xai_key',
            'deepseek': 'deepseek_key',
            'tavily': 'tavily_key',
            'brave': 'brave_key'
        };
        const mappedKey = keyMap[provider.toLowerCase()] || `${provider.toLowerCase()}_key`;
        await (0, parser_1.saveApiKeys)({ [mappedKey]: key });
        console.log(picocolors_1.default.green(`✅ API Key for ${provider} saved securely to vault.`));
        process.exit(0);
    }
    // 2. Setup boilerplate files if in global mode and they don't exist
    let isFirstBoot = false;
    if (isGlobalMode) {
        const globalConfigPath = path_1.default.join(appDir, 'config.yaml');
        const globalUserMdPath = path_1.default.join(appDir, 'user.md');
        const globalIdentityMdPath = path_1.default.join(appDir, 'IDENTITY.md');
        // Copy default config.yaml
        if (!fs_1.default.existsSync(globalConfigPath)) {
            isFirstBoot = true;
            const exampleConfigPath = path_1.default.resolve(__dirname, '../../../config.yaml');
            if (fs_1.default.existsSync(exampleConfigPath)) {
                fs_1.default.copyFileSync(exampleConfigPath, globalConfigPath);
            }
            else {
                fs_1.default.writeFileSync(globalConfigPath, 'agent:\n  name: Nyxora-Agent\n  default_chain: base\nllm:\n  provider: openai\n  model: gpt-4o-mini\n  temperature: 0.2\n  api_keys: []\nmemory:\n  type: file\n  path: memory.json\n');
            }
        }
        if (!fs_1.default.existsSync(globalUserMdPath)) {
            fs_1.default.writeFileSync(globalUserMdPath, 'Write custom instructions, special rules, user profiles, or the persona you want for Nyxora AI in this file.\n');
        }
        if (!fs_1.default.existsSync(globalIdentityMdPath)) {
            fs_1.default.writeFileSync(globalIdentityMdPath, 'You are a Web3 AI assistant named Nyxora.\n');
        }
    }
    if (isFirstBoot) {
        console.log('[Setup] New installation detected. Starting Setup Wizard...');
        await (0, setup_1.runSetupWizard)();
    }
    // 4. Start the Express API Server (which also serves the static dashboard and Telegram bot)
    (0, server_1.startServer)();
    const token = (0, state_1.getSessionToken)(); // Initialize token file
    setTimeout(() => {
        console.log(picocolors_1.default.cyan(`\n✨ Dashboard URL: http://localhost:3000/?token=${token}`));
        console.log(picocolors_1.default.gray(`   (Developers: Vite hot-reload available at http://localhost:5173/?token=${token})\n`));
    }, 1500);
}
main().catch(console.error);
