import { useState, useCallback, useEffect } from 'react'; import api, { getStorageKey } from '../utils/api'; import { useAuth } from './useAuth'; export interface Article { id: string; title: string; content: string; category: string; author_id: string; is_published: boolean; created_at: string; updated_at: string; summary?: string; score?: number; view_count?: number; match_type?: string; snippet?: string; } const KB_CACHE_KEY = 'nexus_kb_v1'; const CACHE_TTL = 300000; // 5 minutes interface KBCache { articles: Article[]; categories: string[]; lastFetched: number; workspaceId: string | null; } let globalKBCache: KBCache = (() => { try { const cached = sessionStorage.getItem(getStorageKey(KB_CACHE_KEY)); return cached ? JSON.parse(cached) : { articles: [], categories: ['All Documentation'], lastFetched: 0, workspaceId: null }; } catch { return { articles: [], categories: ['All Documentation'], lastFetched: 0, workspaceId: null }; } })(); globalKBCache.lastFetched = 0; // Forced background sync on module load let globalKBLoading = false; const kbListeners = new Set<(c: KBCache, l: boolean) => void>(); const notifyKB = () => kbListeners.forEach(l => l(globalKBCache, globalKBLoading)); export const useKnowledgeBase = (workspaceId?: string) => { const [cache, setCache] = useState(globalKBCache); const [loading, setLoading] = useState(globalKBLoading); useEffect(() => { const listener = (c: KBCache, l: boolean) => { setCache(c); setLoading(l); }; kbListeners.add(listener); return () => { kbListeners.delete(listener); }; }, []); const fetchKB = useCallback(async (force: boolean = false) => { const now = Date.now(); const isExpired = now - globalKBCache.lastFetched > CACHE_TTL; const isNewWorkspace = workspaceId && globalKBCache.workspaceId !== workspaceId; if (!force && !isExpired && !isNewWorkspace && globalKBCache.articles.length > 0) return; globalKBLoading = true; notifyKB(); try { // Parallel fetch for speed const [artResp, catResp] = await Promise.all([ api.get('kb/'), api.get('kb/categories/') ]); globalKBCache = { articles: artResp.data || [], categories: ['All Documentation', ...(catResp.data || [])], lastFetched: Date.now(), workspaceId: workspaceId || null }; sessionStorage.setItem(getStorageKey(KB_CACHE_KEY), JSON.stringify(globalKBCache)); } catch (err) { console.error('Failed to fetch Knowledge Base:', err); } finally { globalKBLoading = false; notifyKB(); } }, [workspaceId]); const { token } = useAuth(); useEffect(() => { if (token) { fetchKB(); } }, [fetchKB, token]); return { articles: cache.articles, categories: cache.categories, loading, refresh: () => fetchKB(true) }; };