File size: 9,786 Bytes
b66240d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
const DEFAULT_TTL = 60 * 1000; // 1 minute cache

class ApiClient {
    constructor() {
        // Use current origin by default to avoid hardcoded URLs
        this.baseURL = window.location.origin;
        
        // Allow override via window.BACKEND_URL if needed
        if (typeof window.BACKEND_URL === 'string' && window.BACKEND_URL.trim()) {
            this.baseURL = window.BACKEND_URL.trim().replace(/\/$/, '');
        }

        console.log('[ApiClient] Using Backend:', this.baseURL);

        this.cache = new Map();
        this.requestLogs = [];
        this.errorLogs = [];
        this.logSubscribers = new Set();
        this.errorSubscribers = new Set();
    }

    buildUrl(endpoint) {
        if (!endpoint.startsWith('/')) {
            return `${this.baseURL}/${endpoint}`;
        }
        return `${this.baseURL}${endpoint}`;
    }

    notifyLog(entry) {
        this.requestLogs.push(entry);
        this.requestLogs = this.requestLogs.slice(-100);
        this.logSubscribers.forEach((cb) => cb(entry));
    }

    notifyError(entry) {
        this.errorLogs.push(entry);
        this.errorLogs = this.errorLogs.slice(-100);
        this.errorSubscribers.forEach((cb) => cb(entry));
    }

    onLog(callback) {
        this.logSubscribers.add(callback);
        return () => this.logSubscribers.delete(callback);
    }

    onError(callback) {
        this.errorSubscribers.add(callback);
        return () => this.errorSubscribers.delete(callback);
    }

    getLogs() {
        return [...this.requestLogs];
    }

    getErrors() {
        return [...this.errorLogs];
    }

    async request(method, endpoint, { body, cache = true, ttl = DEFAULT_TTL } = {}) {
        const url = this.buildUrl(endpoint);
        const cacheKey = `${method}:${url}`;

        if (method === 'GET' && cache && this.cache.has(cacheKey)) {
            const cached = this.cache.get(cacheKey);
            if (Date.now() - cached.timestamp < ttl) {
                return { ok: true, data: cached.data, cached: true };
            }
        }

        const started = performance.now();
        const randomId = (window.crypto && window.crypto.randomUUID && window.crypto.randomUUID())
            || `${Date.now()}-${Math.random()}`;
        const entry = {
            id: randomId,
            method,
            endpoint,
            status: 'pending',
            duration: 0,
            time: new Date().toISOString(),
        };

        try {
            const response = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                },
                body: body ? JSON.stringify(body) : undefined,
            });

            const duration = performance.now() - started;
            entry.duration = Math.round(duration);
            entry.status = response.status;

            const contentType = response.headers.get('content-type') || '';
            let data = null;
            if (contentType.includes('application/json')) {
                data = await response.json();
            } else if (contentType.includes('text')) {
                data = await response.text();
            }

            if (!response.ok) {
                const error = new Error((data && data.message) || response.statusText || 'Unknown error');
                error.status = response.status;
                throw error;
            }

            if (method === 'GET' && cache) {
                this.cache.set(cacheKey, { timestamp: Date.now(), data });
            }

            this.notifyLog({ ...entry, success: true });
            return { ok: true, data };
        } catch (error) {
            const duration = performance.now() - started;
            entry.duration = Math.round(duration);
            entry.status = error.status || 'error';
            this.notifyLog({ ...entry, success: false, error: error.message });
            this.notifyError({
                message: error.message,
                endpoint,
                method,
                time: new Date().toISOString(),
            });
            return { ok: false, error: error.message };
        }
    }

    get(endpoint, options) {
        return this.request('GET', endpoint, options);
    }

    post(endpoint, body, options = {}) {
        return this.request('POST', endpoint, { ...options, body });
    }

    // ===== Specific API helpers =====
    // Note: Backend uses api_server_extended.py which has different endpoints
    
    getHealth() {
        // Backend doesn't have /api/health, use /api/status instead
        return this.get('/api/status');
    }

    getTopCoins(limit = 10) {
        // Backend uses /api/market which returns cryptocurrencies array
        return this.get('/api/market').then(result => {
            if (result.ok && result.data && result.data.cryptocurrencies) {
                return {
                    ok: true,
                    data: result.data.cryptocurrencies.slice(0, limit)
                };
            }
            return result;
        });
    }

    getCoinDetails(symbol) {
        // Get from market data and filter by symbol
        return this.get('/api/market').then(result => {
            if (result.ok && result.data && result.data.cryptocurrencies) {
                const coin = result.data.cryptocurrencies.find(
                    c => c.symbol.toUpperCase() === symbol.toUpperCase()
                );
                return coin ? { ok: true, data: coin } : { ok: false, error: 'Coin not found' };
            }
            return result;
        });
    }

    getMarketStats() {
        // Backend returns stats in /api/market response
        return this.get('/api/market').then(result => {
            if (result.ok && result.data) {
                return {
                    ok: true,
                    data: {
                        total_market_cap: result.data.total_market_cap,
                        btc_dominance: result.data.btc_dominance,
                        total_volume_24h: result.data.total_volume_24h,
                        market_cap_change_24h: result.data.market_cap_change_24h
                    }
                };
            }
            return result;
        });
    }

    getLatestNews(limit = 20) {
        // Backend doesn't have news endpoint yet, return empty for now
        return Promise.resolve({ 
            ok: true, 
            data: { 
                articles: [],
                message: 'News endpoint not yet implemented in backend'
            } 
        });
    }

    getProviders() {
        return this.get('/api/providers');
    }

    getPriceChart(symbol, timeframe = '7d') {
        // Backend uses /api/ohlcv
        const cleanSymbol = encodeURIComponent(String(symbol || 'BTC').trim().toUpperCase());
        // Map timeframe to interval and limit
        const intervalMap = { '1d': '1h', '7d': '1h', '30d': '4h', '90d': '1d', '365d': '1d' };
        const limitMap = { '1d': 24, '7d': 168, '30d': 180, '90d': 90, '365d': 365 };
        const interval = intervalMap[timeframe] || '1h';
        const limit = limitMap[timeframe] || 168;
        return this.get(`/api/ohlcv?symbol=${cleanSymbol}USDT&interval=${interval}&limit=${limit}`);
    }

    analyzeChart(symbol, timeframe = '7d', indicators = []) {
        // Not implemented in backend yet
        return Promise.resolve({ 
            ok: false, 
            error: 'Chart analysis not yet implemented in backend' 
        });
    }

    runQuery(payload) {
        // Not implemented in backend yet
        return Promise.resolve({ 
            ok: false, 
            error: 'Query endpoint not yet implemented in backend' 
        });
    }

    analyzeSentiment(payload) {
        // Backend has /api/sentiment but it returns market sentiment, not text analysis
        // For now, return the market sentiment
        return this.get('/api/sentiment');
    }

    summarizeNews(item) {
        // Not implemented in backend yet
        return Promise.resolve({ 
            ok: false, 
            error: 'News summarization not yet implemented in backend' 
        });
    }

    getDatasetsList() {
        // Not implemented in backend yet
        return Promise.resolve({ 
            ok: true, 
            data: { 
                datasets: [],
                message: 'Datasets endpoint not yet implemented in backend'
            } 
        });
    }

    getDatasetSample(name) {
        // Not implemented in backend yet
        return Promise.resolve({ 
            ok: false, 
            error: 'Dataset sample not yet implemented in backend' 
        });
    }

    getModelsList() {
        // Backend has /api/hf/models
        return this.get('/api/hf/models');
    }

    testModel(payload) {
        // Not implemented in backend yet
        return Promise.resolve({ 
            ok: false, 
            error: 'Model testing not yet implemented in backend' 
        });
    }
    
    // ===== Additional methods for backend compatibility =====
    
    getTrending() {
        return this.get('/api/trending');
    }
    
    getStats() {
        return this.get('/api/stats');
    }
    
    getHFHealth() {
        return this.get('/api/hf/health');
    }
    
    runDiagnostics(autoFix = false) {
        return this.post('/api/diagnostics/run', { auto_fix: autoFix });
    }
    
    getLastDiagnostics() {
        return this.get('/api/diagnostics/last');
    }
    
    runAPLScan() {
        return this.post('/api/apl/run');
    }
    
    getAPLReport() {
        return this.get('/api/apl/report');
    }
    
    getAPLSummary() {
        return this.get('/api/apl/summary');
    }
}

const apiClient = new ApiClient();
export default apiClient;