Spaces:
Paused

File size: 2,923 Bytes
b91e6a1
 
0fe602d
b91e6a1
 
 
 
 
 
 
 
 
 
 
 
226650c
b91e6a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d679552
b91e6a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe602d
7b3791b
b91e6a1
0fe602d
 
 
 
b91e6a1
7b3791b
 
 
 
 
b91e6a1
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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)
  };
};