"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadApiKeys = loadApiKeys;
exports.saveApiKeys = saveApiKeys;
exports.loadConfig = loadConfig;
exports.saveConfig = saveConfig;
const fs_1 = __importDefault(require("fs"));
const yaml_1 = __importDefault(require("yaml"));
const paths_1 = require("./paths");
async function loadApiKeys() {
    const vaultPath = (0, paths_1.getPath)('api_vault.key');
    try {
        const { Entry } = require('@napi-rs/keyring');
        const entry = new Entry('nyxora', 'api_keys');
        const data = await entry.getPassword();
        if (data)
            return JSON.parse(data);
    }
    catch (e) {
        if (fs_1.default.existsSync(vaultPath)) {
            try {
                const file = fs_1.default.readFileSync(vaultPath, 'utf8');
                return JSON.parse(file);
            }
            catch (err) { }
        }
    }
    return {};
}
async function saveApiKeys(newKeys) {
    const vaultPath = (0, paths_1.getPath)('api_vault.key');
    const currentKeys = await loadApiKeys();
    const mergedKeys = { ...currentKeys, ...newKeys };
    const dataString = JSON.stringify(mergedKeys);
    try {
        const { Entry } = require('@napi-rs/keyring');
        const entry = new Entry('nyxora', 'api_keys');
        await entry.setPassword(dataString);
    }
    catch (e) {
        fs_1.default.writeFileSync(vaultPath, dataString, { mode: 0o600 });
    }
}
function loadConfig() {
    const configPath = (0, paths_1.getPath)('config.yaml');
    try {
        const file = fs_1.default.readFileSync(configPath, 'utf8');
        const parsed = yaml_1.default.parse(file);
        // Auto-migration logic: move llm.credentials to root credentials
        let needsSave = false;
        if (parsed.llm && parsed.llm.credentials) {
            if (!parsed.credentials) {
                parsed.credentials = {};
            }
            const oldCreds = parsed.llm.credentials;
            Object.keys(oldCreds).forEach(key => {
                if (oldCreds[key] && !parsed.credentials[key]) {
                    parsed.credentials[key] = oldCreds[key];
                }
            });
            delete parsed.llm.credentials;
            needsSave = true;
        }
        if (needsSave) {
            try {
                const yamlStr = yaml_1.default.stringify(parsed);
                fs_1.default.writeFileSync(configPath, yamlStr, 'utf8');
                console.log('[Config] Auto-migrated llm.credentials to root credentials.');
            }
            catch (e) {
                console.error('[Config] Failed to auto-migrate config file', e);
            }
        }
        // Auto-migrate from config.yaml to Keyring/Vault
        if (parsed.credentials && Object.keys(parsed.credentials).length > 0) {
            const credsToMigrate = { ...parsed.credentials };
            saveApiKeys(credsToMigrate).then(() => {
                console.log('[Config] Auto-migrated API keys to secure vault.');
                delete parsed.credentials;
                try {
                    const yamlStr = yaml_1.default.stringify(parsed);
                    fs_1.default.writeFileSync(configPath, yamlStr, 'utf8');
                }
                catch (e) { }
            }).catch(e => {
                console.error('[Config] Failed to migrate API keys to secure vault', e);
            });
        }
        return {
            agent: parsed.agent || { name: 'Nyxora-Default', description: 'Your Personal Web3 Assistant.', default_chain: 'base', default_router: 'auto', default_slippage: 0.5 },
            llm: parsed.llm || {
                provider: 'openai',
                model: 'gpt-4o-mini',
                temperature: 0.2,
                api_keys: []
            },
            web_search: parsed.web_search || {
                provider: 'mesh',
                enabled: true
            },
            credentials: parsed.credentials || {},
            memory: parsed.memory || { type: 'file', path: './memory.json' },
            web3: parsed.web3 || { rpc_urls: {} },
            integrations: parsed.integrations || {
                telegram: { enabled: false }
            },
            permissions: parsed.permissions || {
                web3: { allow_transfer: true, allow_swap: true, max_usd_per_tx: 999999999 },
                system: { allow_shell_execution: true, allow_file_write: true }
            }
        };
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            console.log('[Config] No config.yaml found. Using default configuration.');
        }
        else {
            console.error('[Config] Failed to load config.yaml. Using default configuration.', error);
        }
        return {
            agent: {
                name: "Nyxora-Default",
                description: "Your Personal Web3 Assistant.",
                default_chain: "ethereum",
                default_router: "auto",
                default_slippage: 0.5
            },
            llm: {
                provider: 'openai',
                model: 'gpt-4o-mini',
                temperature: 0.2,
                api_keys: []
            },
            web_search: {
                provider: 'mesh',
                enabled: true
            },
            credentials: {},
            memory: { type: 'file', path: './memory.json' },
            web3: { rpc_urls: {} },
            integrations: {
                telegram: { enabled: false }
            },
            permissions: {
                web3: { allow_transfer: true, allow_swap: true, max_usd_per_tx: 999999999 },
                system: { allow_shell_execution: true, allow_file_write: true }
            }
        };
    }
}
function saveConfig(newConfig) {
    const configPath = (0, paths_1.getPath)('config.yaml');
    try {
        const yamlStr = yaml_1.default.stringify(newConfig);
        fs_1.default.writeFileSync(configPath, yamlStr, 'utf8');
    }
    catch (error) {
        console.error('Failed to save config.yaml', error);
    }
}
