import { readFileSync, writeFileSync } from 'fs';
import { getClosestConfigFile } from '../config/index.js';
import { logError } from '../utils/message-queue.js';
let PREFERENCES_PATH = null;
let CACHED_CONFIG_DIR = undefined;
function getPreferencesPath() {
    // Re-compute path if NANOCODER_CONFIG_DIR has changed (important for tests)
    const currentConfigDir = process.env.NANOCODER_CONFIG_DIR;
    if (!PREFERENCES_PATH || CACHED_CONFIG_DIR !== currentConfigDir) {
        PREFERENCES_PATH = getClosestConfigFile('nanocoder-preferences.json');
        CACHED_CONFIG_DIR = currentConfigDir;
    }
    return PREFERENCES_PATH;
}
// Export for testing purposes - allows tests to reset the cache
export function resetPreferencesCache() {
    PREFERENCES_PATH = null;
    CACHED_CONFIG_DIR = undefined;
}
export function loadPreferences() {
    try {
        const data = readFileSync(getPreferencesPath(), 'utf-8');
        return JSON.parse(data);
    }
    catch (error) {
        logError(`Failed to load preferences: ${String(error)}`);
    }
    return {};
}
export function savePreferences(preferences) {
    try {
        writeFileSync(getPreferencesPath(), JSON.stringify(preferences, null, 2));
    }
    catch (error) {
        logError(`Failed to save preferences: ${String(error)}`);
    }
}
export function updateLastUsed(provider, model) {
    const preferences = loadPreferences();
    preferences.lastProvider = provider;
    preferences.lastModel = model;
    // Also save the model for this specific provider
    if (!preferences.providerModels) {
        preferences.providerModels = {};
    }
    preferences.providerModels[provider] = model;
    savePreferences(preferences);
}
export function updateTitleShape(shape) {
    const preferences = loadPreferences();
    preferences.titleShape = shape;
    savePreferences(preferences);
}
export function getTitleShape() {
    const preferences = loadPreferences();
    return preferences.titleShape;
}
export function getLastUsedModel(provider) {
    const preferences = loadPreferences();
    return preferences.providerModels?.[provider];
}
//# sourceMappingURL=preferences.js.map