import Conf from 'conf';
import fs from 'node:fs';
import { ensureYagrHomeDir, getYagrPaths } from './yagr-home.js';
export function normalizeGatewaySurfaces(surfaces) {
    const normalized = [];
    for (const surface of surfaces ?? []) {
        if ((surface === 'telegram' || surface === 'webui' || surface === 'whatsapp') && !normalized.includes(surface)) {
            normalized.push(surface);
        }
    }
    return normalized;
}
export class YagrConfigService {
    globalStore;
    localConfigPath;
    legacyCredentialsPath;
    constructor() {
        const paths = getYagrPaths();
        ensureYagrHomeDir();
        this.globalStore = new Conf({
            cwd: paths.homeDir,
            configName: 'credentials',
        });
        this.localConfigPath = paths.yagrConfigPath;
        this.legacyCredentialsPath = paths.legacyYagrCredentialsPath;
        this.migrateLegacyCredentials();
    }
    getLocalConfig() {
        if (!fs.existsSync(this.localConfigPath)) {
            return {};
        }
        try {
            const content = fs.readFileSync(this.localConfigPath, 'utf-8');
            return JSON.parse(content);
        }
        catch {
            return {};
        }
    }
    saveLocalConfig(config) {
        fs.writeFileSync(this.localConfigPath, JSON.stringify(config, null, 2));
    }
    updateLocalConfig(updater) {
        const nextConfig = updater(this.getLocalConfig());
        this.saveLocalConfig(nextConfig);
        return nextConfig;
    }
    getEnabledGatewaySurfaces() {
        const localConfig = this.getLocalConfig();
        if (Array.isArray(localConfig.gateway?.enabledSurfaces)) {
            return normalizeGatewaySurfaces(localConfig.gateway.enabledSurfaces);
        }
        if (localConfig.telegram) {
            return ['telegram'];
        }
        return [];
    }
    setEnabledGatewaySurfaces(surfaces) {
        const nextSurfaces = normalizeGatewaySurfaces(surfaces);
        return this.updateLocalConfig((localConfig) => ({
            ...localConfig,
            gateway: {
                ...localConfig.gateway,
                enabledSurfaces: nextSurfaces,
            },
        }));
    }
    enableGatewaySurface(surface) {
        const nextSurfaces = normalizeGatewaySurfaces([...this.getEnabledGatewaySurfaces(), surface]);
        return this.setEnabledGatewaySurfaces(nextSurfaces);
    }
    disableGatewaySurface(surface) {
        const nextSurfaces = this.getEnabledGatewaySurfaces().filter((entry) => entry !== surface);
        return this.setEnabledGatewaySurfaces(nextSurfaces);
    }
    getApiKey(provider) {
        const credentials = this.globalStore.get('providers') ?? {};
        return credentials[provider];
    }
    saveApiKey(provider, apiKey) {
        const credentials = this.globalStore.get('providers') ?? {};
        credentials[provider] = apiKey;
        this.globalStore.set('providers', credentials);
    }
    hasApiKey(provider) {
        return Boolean(this.getApiKey(provider));
    }
    clearLocalConfig() {
        if (fs.existsSync(this.localConfigPath)) {
            fs.unlinkSync(this.localConfigPath);
        }
    }
    clearAllApiKeys() {
        this.globalStore.set('providers', {});
    }
    getTelegramBotToken() {
        return this.globalStore.get('telegram.botToken');
    }
    saveTelegramBotToken(botToken) {
        this.globalStore.set('telegram.botToken', botToken);
    }
    clearTelegramBotToken() {
        this.globalStore.delete('telegram.botToken');
    }
    migrateLegacyCredentials() {
        if (this.globalStore.path === this.legacyCredentialsPath) {
            return;
        }
        const currentProviders = this.globalStore.get('providers') ?? {};
        const currentBotToken = this.globalStore.get('telegram.botToken');
        if ((Object.keys(currentProviders).length > 0 || currentBotToken) || !fs.existsSync(this.legacyCredentialsPath)) {
            return;
        }
        try {
            const content = JSON.parse(fs.readFileSync(this.legacyCredentialsPath, 'utf-8'));
            if (content.providers && Object.keys(content.providers).length > 0) {
                this.globalStore.set('providers', content.providers);
            }
            if (content.telegram?.botToken) {
                this.globalStore.set('telegram.botToken', content.telegram.botToken);
            }
        }
        catch {
            // Ignore malformed legacy files and start fresh in the Yagr home.
        }
    }
}
//# sourceMappingURL=yagr-config-service.js.map