const STORAGE_PREFIX = 'genesis-ai-assistant:cost-history:';
/** localStorage key for a host-scoped cost history list. */
export function costHistoryStorageKey(scope) {
    return `${STORAGE_PREFIX}${scope}`;
}
/** Load persisted cost sessions for a scope (newest first). */
export function loadCostSessionHistory(scope) {
    if (typeof localStorage === 'undefined')
        return [];
    try {
        const raw = localStorage.getItem(costHistoryStorageKey(scope));
        if (!raw)
            return [];
        const parsed = JSON.parse(raw);
        if (!Array.isArray(parsed))
            return [];
        return parsed.filter(isCostSessionRecord);
    }
    catch (_a) {
        return [];
    }
}
/** Replace the persisted list for a scope. */
export function saveCostSessionHistory(scope, records) {
    if (typeof localStorage === 'undefined')
        return;
    try {
        localStorage.setItem(costHistoryStorageKey(scope), JSON.stringify(records));
    }
    catch (_a) {
        // Quota exceeded or private browsing — non-fatal.
    }
}
/** Prepend a record and persist. Returns the updated list. */
export function appendCostSessionRecord(scope, record) {
    const records = [record, ...loadCostSessionHistory(scope)];
    saveCostSessionHistory(scope, records);
    return records;
}
/** Remove one record by id. Returns the updated list. */
export function removeCostSessionRecord(scope, id) {
    const records = loadCostSessionHistory(scope).filter((r) => r.id !== id);
    saveCostSessionHistory(scope, records);
    return records;
}
/** Clear all persisted records for a scope. */
export function clearCostSessionHistory(scope) {
    if (typeof localStorage === 'undefined')
        return;
    try {
        localStorage.removeItem(costHistoryStorageKey(scope));
    }
    catch (_a) {
        // Non-fatal.
    }
}
/** Display date for a history row (e.g. "Jun 14, 2026"). */
export function formatCostSessionDate(iso) {
    return new Intl.DateTimeFormat('en-US', {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
    }).format(new Date(iso));
}
function isCostSessionRecord(value) {
    if (typeof value !== 'object' || value == null)
        return false;
    const r = value;
    return (typeof r.id === 'string' &&
        typeof r.title === 'string' &&
        typeof r.endedAt === 'string' &&
        typeof r.costUsd === 'number' &&
        typeof r.tokensConsumed === 'number' &&
        Array.isArray(r.models));
}
