import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
export const DEFAULT_MODEL = 'openrouter/auto';
function readJsonSafe(file) {
    try {
        return JSON.parse(fs.readFileSync(file, 'utf8'));
    }
    catch {
        return {};
    }
}
export function configDir() {
    return path.join(os.homedir(), '.config', 'cheapcode');
}
export function loadConfig(cwd) {
    const globalCfg = readJsonSafe(path.join(configDir(), 'config.json'));
    const projectCfg = readJsonSafe(path.join(cwd, '.cheapcode', 'settings.json'));
    // CheapCode account keys (cc-sk-...) hit the CheapCode API; a legacy
    // OpenRouter key (sk-or-...) still works BYO-key against OpenRouter.
    const apiKey = process.env.CHEAPCODE_API_KEY ||
        process.env.OPENROUTER_API_KEY ||
        (typeof globalCfg.apiKey === 'string' ? globalCfg.apiKey : null);
    const model = (typeof projectCfg.model === 'string' && projectCfg.model) ||
        (typeof globalCfg.model === 'string' && globalCfg.model) ||
        DEFAULT_MODEL;
    const provider = (projectCfg.provider && typeof projectCfg.provider === 'object' && projectCfg.provider) ||
        (globalCfg.provider && typeof globalCfg.provider === 'object' && globalCfg.provider) ||
        null;
    // Project MCP servers and hooks are merged over global ones.
    const mcpServers = {
        ...(globalCfg.mcpServers && typeof globalCfg.mcpServers === 'object' ? globalCfg.mcpServers : {}),
        ...(projectCfg.mcpServers && typeof projectCfg.mcpServers === 'object' ? projectCfg.mcpServers : {}),
    };
    const hooks = {
        ...(globalCfg.hooks && typeof globalCfg.hooks === 'object' ? globalCfg.hooks : {}),
        ...(projectCfg.hooks && typeof projectCfg.hooks === 'object' ? projectCfg.hooks : {}),
    };
    return { apiKey, model, provider, mcpServers, hooks };
}
export function saveGlobalConfig(patch) {
    const dir = configDir();
    fs.mkdirSync(dir, { recursive: true });
    const file = path.join(dir, 'config.json');
    const current = readJsonSafe(file);
    fs.writeFileSync(file, JSON.stringify({ ...current, ...patch }, null, 2) + '\n');
}
