"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LlmConfig = void 0;
exports.getBuiltinDefaultsYamlPath = getBuiltinDefaultsYamlPath;
exports.readBuiltinDefaultsYamlRaw = readBuiltinDefaultsYamlRaw;
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
const yaml_1 = __importDefault(require("yaml"));
const log_1 = require("../log");
const BUILTIN_DEFAULTS_YAML_PATH = path_1.default.join(__dirname, 'defaults.yaml');
// Special-case cache: built-in defaults are immutable at runtime, so this file may be cached
// forever to survive dogfooding rebuild windows. Do not generalize this to rtws/user-editable files.
let builtinDefaultsYamlRawCache;
let builtinDefaultsYamlRawReadPromise;
/**
 * LlmConfig
 *
 * Wraps provider configurations and exposes lookup helpers.
 */
class LlmConfig {
    _providers;
    constructor(providers) {
        this._providers = providers;
    }
    get providers() {
        return this._providers;
    }
    getProvider(providerKey) {
        return this._providers[providerKey];
    }
}
exports.LlmConfig = LlmConfig;
(function (LlmConfig) {
    async function load() {
        // Load default providers from YAML file
        const rawDefaults = await readBuiltinDefaultsYamlRaw();
        const parsedDefaults = yaml_1.default.parse(rawDefaults);
        if (!isRecord(parsedDefaults) || !isRecord(parsedDefaults.providers)) {
            throw new Error('Invalid defaults.yaml: expected providers object');
        }
        const defaultProviders = parsedDefaults.providers;
        // Load rtws configuration
        const cfgPath = '.minds/llm.yaml';
        let workspaceProviders = {};
        try {
            await promises_1.default.access(cfgPath);
            try {
                const raw = await promises_1.default.readFile(cfgPath, 'utf-8');
                const parsed = yaml_1.default.parse(raw);
                const providers = isRecord(parsed) ? parsed.providers : undefined;
                if (isRecord(providers)) {
                    workspaceProviders = providers;
                }
                else {
                    throw new Error('Invalid llm.yaml: missing providers object');
                }
            }
            catch (error) {
                log_1.log.warn('Could not load rtws llm.yaml:', error);
            }
        }
        catch (err) {
            log_1.log.debug('No rtws llm.yaml found, using defaults');
        }
        // Merge defaults with rtws config (rtws overrides defaults)
        const mergedProviders = { ...defaultProviders, ...workspaceProviders };
        return new LlmConfig(mergedProviders);
    }
    LlmConfig.load = load;
})(LlmConfig || (exports.LlmConfig = LlmConfig = {}));
function getBuiltinDefaultsYamlPath() {
    return BUILTIN_DEFAULTS_YAML_PATH;
}
async function readBuiltinDefaultsYamlRaw() {
    if (builtinDefaultsYamlRawCache !== undefined)
        return builtinDefaultsYamlRawCache;
    if (builtinDefaultsYamlRawReadPromise === undefined) {
        builtinDefaultsYamlRawReadPromise = promises_1.default
            .readFile(BUILTIN_DEFAULTS_YAML_PATH, 'utf-8')
            .then((raw) => {
            const parsed = yaml_1.default.parse(raw);
            if (!isRecord(parsed) || !isRecord(parsed.providers)) {
                throw new Error('Invalid defaults.yaml: expected providers object');
            }
            builtinDefaultsYamlRawCache = raw;
            return raw;
        })
            .catch((error) => {
            builtinDefaultsYamlRawReadPromise = undefined;
            throw error;
        });
    }
    return builtinDefaultsYamlRawReadPromise;
}
function isRecord(value) {
    return typeof value === 'object' && value !== null;
}
