import { Telemetry } from "../util/posthog.js";
import { finalToBrowserConfig, loadFullConfigNode } from "./load.js";
export class ConfigHandler {
    ide;
    ideSettingsPromise;
    writeLog;
    savedConfig;
    savedBrowserConfig;
    additionalContextProviders = [];
    constructor(ide, ideSettingsPromise, writeLog) {
        this.ide = ide;
        this.ideSettingsPromise = ideSettingsPromise;
        this.writeLog = writeLog;
        this.ide = ide;
        this.ideSettingsPromise = ideSettingsPromise;
        this.writeLog = writeLog;
        try {
            this.loadConfig();
        }
        catch (e) {
            console.error("Failed to load config: ", e);
        }
    }
    updateIdeSettings(ideSettings) {
        this.ideSettingsPromise = Promise.resolve(ideSettings);
        this.reloadConfig();
    }
    updateListeners = [];
    onConfigUpdate(listener) {
        this.updateListeners.push(listener);
    }
    reloadConfig() {
        this.savedConfig = undefined;
        this.savedBrowserConfig = undefined;
        this.loadConfig();
        for (const listener of this.updateListeners) {
            listener();
        }
    }
    async getSerializedConfig() {
        if (!this.savedBrowserConfig) {
            this.savedConfig = await this.loadConfig();
            this.savedBrowserConfig = finalToBrowserConfig(this.savedConfig);
        }
        return this.savedBrowserConfig;
    }
    async loadConfig() {
        if (this.savedConfig) {
            return this.savedConfig;
        }
        let workspaceConfigs = [];
        try {
            workspaceConfigs = await this.ide.getWorkspaceConfigs();
        }
        catch (e) {
            console.warn("Failed to load workspace configs");
        }
        const ideInfo = await this.ide.getIdeInfo();
        const uniqueId = await this.ide.getUniqueId();
        this.savedConfig = await loadFullConfigNode(this.ide, workspaceConfigs, await this.ideSettingsPromise, ideInfo.ideType, uniqueId, this.writeLog);
        this.savedConfig.allowAnonymousTelemetry =
            this.savedConfig.allowAnonymousTelemetry &&
                (await this.ide.isTelemetryEnabled());
        // Setup telemetry only after (and if) we know it is enabled
        await Telemetry.setup(this.savedConfig.allowAnonymousTelemetry ?? true, await this.ide.getUniqueId(), ideInfo.extensionVersion);
        (this.savedConfig.contextProviders ?? []).push(...this.additionalContextProviders);
        return this.savedConfig;
    }
    async llmFromTitle(title) {
        const config = await this.loadConfig();
        const model = config.models.find((m) => m.title === title) || config.models[0];
        if (!model) {
            throw new Error("No model found");
        }
        return model;
    }
    registerCustomContextProvider(contextProvider) {
        this.additionalContextProviders.push(contextProvider);
        this.reloadConfig();
    }
}
