export interface LogQLHistoryItem { query: string; usageCount: number; lastUsedAt: number; } const MAX_HISTORY_ITEMS = 20; const MAX_COMPLETION_ITEMS = 10; function isHistoryItem(value: unknown): value is LogQLHistoryItem { if (typeof value !== 'object' || value === null) return false; const item = value as Record; return ( typeof item.query === 'string' && item.query.trim().length > 0 && typeof item.usageCount === 'number' && Number.isFinite(item.usageCount) && item.usageCount > 0 && typeof item.lastUsedAt === 'number' && Number.isFinite(item.lastUsedAt) ); } function sortByUsage(items: LogQLHistoryItem[]): LogQLHistoryItem[] { return [...items].sort((a, b) => b.usageCount - a.usageCount || b.lastUsedAt - a.lastUsedAt); } export function readHistory(historyKey: string | undefined): LogQLHistoryItem[] { if (!historyKey || typeof window === 'undefined') return []; try { const value = window.localStorage.getItem(historyKey); if (!value) return []; const parsed: unknown = JSON.parse(value); if (!Array.isArray(parsed)) return []; return sortByUsage(parsed.filter(isHistoryItem)).slice(0, MAX_HISTORY_ITEMS); } catch { return []; } } export function saveHistory(historyKey: string | undefined, query: string, now = Date.now()): LogQLHistoryItem[] { const normalizedQuery = query.trim(); if (!historyKey || !normalizedQuery || typeof window === 'undefined') return []; const history = readHistory(historyKey); const existing = history.find((item) => item.query === normalizedQuery); const next = existing ? history.map((item) => (item === existing ? { ...item, usageCount: item.usageCount + 1, lastUsedAt: now } : item)) : [...history, { query: normalizedQuery, usageCount: 1, lastUsedAt: now }]; const sorted = sortByUsage(next).slice(0, MAX_HISTORY_ITEMS); try { window.localStorage.setItem(historyKey, JSON.stringify(sorted)); } catch { // Storage may be unavailable (e.g. private browsing or a full quota). } return sorted; } export function getHistoryCompletionItems(historyKey: string | undefined): LogQLHistoryItem[] { return readHistory(historyKey).slice(0, MAX_COMPLETION_ITEMS); }