import { readJson, writeJson, globalDataDir } from './base-store.js';
import { withFileLock } from './file-mutex.js';
import { applyLearnedLimit, markVerified } from '../engine/registry-extender.js';
// --- file paths ---
function configFile() {
    return `${globalDataDir()}/config.json`;
}
function templatesFile() {
    return `${globalDataDir()}/templates.json`;
}
function pricingFile() {
    return `${globalDataDir()}/pricing.json`;
}
// --- defaults ---
const DEFAULT_CONFIG = {
    defaultLocale: 'en',
    defaultExperienceLevel: 'intermediate',
    hourlyRate: 50,
    pricingOpusPerMToken: 15,
    pricingSonnetPerMToken: 3,
};
// TemplateMap and PricingMap imported from types/index.js
// --- Global Config ---
/**
 * Get the global configuration. Returns defaults when no config file exists.
 */
export async function getGlobalConfig() {
    return readJson(configFile(), DEFAULT_CONFIG);
}
/**
 * Save the full global configuration.
 */
export async function saveGlobalConfig(config) {
    await writeJson(configFile(), config);
}
/**
 * Partially update the global configuration.
 */
export async function updateGlobalConfig(updates) {
    const existing = await getGlobalConfig();
    const updated = { ...existing, ...updates };
    await writeJson(configFile(), updated);
    return updated;
}
/**
 * Set the default locale globally.
 */
export async function setDefaultLocale(locale) {
    return updateGlobalConfig({ defaultLocale: locale });
}
/**
 * Set the default experience level globally.
 */
export async function setDefaultExperienceLevel(level) {
    return updateGlobalConfig({ defaultExperienceLevel: level });
}
/**
 * Set the hourly rate globally.
 */
export async function setHourlyRate(rate) {
    return updateGlobalConfig({ hourlyRate: rate });
}
// --- Templates ---
/**
 * Get all stored templates.
 */
export async function getTemplates() {
    return readJson(templatesFile(), {});
}
/**
 * Get a single template by key. Returns `null` when not found.
 */
export async function getTemplate(key) {
    const templates = await getTemplates();
    return templates[key] ?? null;
}
/**
 * Set or overwrite a template by key.
 */
export async function setTemplate(key, template) {
    await withFileLock(templatesFile(), async () => {
        const templates = await getTemplates();
        templates[key] = template;
        await writeJson(templatesFile(), templates);
    });
}
/**
 * Delete a template by key. Returns `true` if it existed.
 */
export async function deleteTemplate(key) {
    return withFileLock(templatesFile(), async () => {
        const templates = await getTemplates();
        if (!(key in templates)) {
            return false;
        }
        const { [key]: _, ...rest } = templates;
        await writeJson(templatesFile(), rest);
        return true;
    });
}
/**
 * List all template keys.
 */
export async function listTemplateKeys() {
    const templates = await getTemplates();
    return Object.keys(templates);
}
// --- Pricing ---
/**
 * Get all pricing data.
 */
export async function getPricing() {
    return readJson(pricingFile(), {});
}
/**
 * Get a pricing tier by key.
 */
export async function getPricingTier(key) {
    const pricing = await getPricing();
    return pricing[key] ?? null;
}
/**
 * Set or overwrite a pricing tier.
 */
export async function setPricingTier(key, tier) {
    await withFileLock(pricingFile(), async () => {
        const pricing = await getPricing();
        pricing[key] = tier;
        await writeJson(pricingFile(), pricing);
    });
}
/**
 * Delete a pricing tier. Returns `true` if it existed.
 */
export async function deletePricingTier(key) {
    return withFileLock(pricingFile(), async () => {
        const pricing = await getPricing();
        if (!(key in pricing)) {
            return false;
        }
        const { [key]: _, ...rest } = pricing;
        await writeJson(pricingFile(), rest);
        return true;
    });
}
// --- Learned Registries (SPEC-011) ---
function learnedRegistriesFile() {
    return `${globalDataDir()}/learned-registries.json`;
}
/**
 * Get all learned registry entries across all registry types.
 */
export async function getLearnedRegistries() {
    return readJson(learnedRegistriesFile(), []);
}
/**
 * Add a new learned entry if it doesn't already exist (deduplication by id).
 * Applies LRU eviction when limit of 500 is exceeded.
 * Returns the updated entries list.
 */
export async function addLearnedEntry(entry) {
    return withFileLock(learnedRegistriesFile(), async () => {
        const entries = await getLearnedRegistries();
        if (entries.find((e) => e.id === entry.id)) {
            return entries;
        }
        const updated = applyLearnedLimit([...entries, entry]);
        await writeJson(learnedRegistriesFile(), updated);
        return updated;
    });
}
/**
 * Get all learned entries for a specific registry type.
 */
export async function getLearnedEntriesByRegistry(registry) {
    const all = await getLearnedRegistries();
    return all.filter((e) => e.registry === registry);
}
/**
 * Mark a learned entry as verified. Returns `true` if the entry was found.
 */
export async function markLearnedEntryVerified(entryId) {
    const entries = await getLearnedRegistries();
    const { updated, found } = markVerified(entries, entryId);
    if (found) {
        await writeJson(learnedRegistriesFile(), updated);
    }
    return found;
}
// --- Token Usage (SPEC-012) ---
function tokenUsageFile() {
    return `${globalDataDir()}/token-usage.json`;
}
export async function getTokenUsages() {
    return readJson(tokenUsageFile(), []);
}
export async function saveTokenUsage(usage) {
    await withFileLock(tokenUsageFile(), async () => {
        const all = await getTokenUsages();
        // Keep last 1000 entries (rolling window)
        const trimmed = all.length >= 1000 ? all.slice(-999) : all;
        await writeJson(tokenUsageFile(), [...trimmed, usage]);
    });
}
// --- Developer Preferences (SPEC-012) ---
function developerPreferencesFile() {
    return `${globalDataDir()}/developer-preferences.json`;
}
export async function getDeveloperPreferences() {
    return readJson(developerPreferencesFile(), []);
}
export async function recordDeveloperPreference(tool, action) {
    await withFileLock(developerPreferencesFile(), async () => {
        const prefs = await getDeveloperPreferences();
        const existing = prefs.find((p) => p.tool === tool && p.action === action);
        if (existing) {
            existing.count += 1;
            existing.lastSeen = new Date().toISOString();
        }
        else {
            prefs.push({ tool, action, count: 1, lastSeen: new Date().toISOString() });
        }
        await writeJson(developerPreferencesFile(), prefs);
    });
}
// --- Improvement Overrides (SPEC-012) ---
function improvementOverridesFile() {
    return `${globalDataDir()}/improvement-overrides.json`;
}
export async function getImprovementOverrides() {
    return readJson(improvementOverridesFile(), []);
}
export async function saveImprovementOverride(override) {
    const overrides = await getImprovementOverrides();
    if (!overrides.find((o) => o.id === override.id)) {
        overrides.push(override);
        await writeJson(improvementOverridesFile(), overrides);
    }
}
// --- Lessons Learned (SPEC-012) ---
function lessonsLearnedFile() {
    return `${globalDataDir()}/lessons-learned.json`;
}
export async function getLessonsLearned() {
    return readJson(lessonsLearnedFile(), []);
}
export async function saveLessonLearned(lesson) {
    await withFileLock(lessonsLearnedFile(), async () => {
        const lessons = await getLessonsLearned();
        if (!lessons.find((l) => l.id === lesson.id)) {
            lessons.push(lesson);
            await writeJson(lessonsLearnedFile(), lessons);
        }
    });
}
export async function findLessons(tags) {
    const all = await getLessonsLearned();
    if (tags.length === 0) {
        return all;
    }
    return all.filter((l) => tags.some((tag) => l.tags.includes(tag)));
}
//# sourceMappingURL=global-store.js.map