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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/**

 * API Client for Crypto Monitor ULTIMATE

 * 

 * Features:

 * - Pure HTTP/Fetch API (NO WEBSOCKET)

 * - Simple caching mechanism

 * - Automatic retry logic

 * - Request/error logging

 * - ES6 module exports

 */

import { CONFIG, API_ENDPOINTS, buildApiUrl, getCacheKey } from './config.js';

/**

 * Base API Client with caching and retry

 */
class APIClient {
  constructor(baseURL = CONFIG.API_BASE_URL) {
    this.baseURL = baseURL;
    this.cache = new Map();
    this.cacheTTL = CONFIG.CACHE_TTL;
    this.maxRetries = CONFIG.MAX_RETRIES;
    this.retryDelay = CONFIG.RETRY_DELAY;
    this.requestLog = [];
    this.errorLog = [];
    this.maxLogSize = 100;
  }

  /**

   * Core request method with retry logic

   */
  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    const method = options.method || 'GET';
    const startTime = performance.now();

    // Check cache for GET requests (but skip cache for models/status to get fresh data)
    if (method === 'GET' && !options.skipCache) {
      // Don't cache models status/summary - always get fresh data
      const shouldSkipCache = endpoint.includes('/models/status') || 
                             endpoint.includes('/models/summary') ||
                             options.forceRefresh;
      
      if (!shouldSkipCache) {
        const cached = this._getFromCache(endpoint);
        if (cached) {
          console.log(`[APIClient] Cache hit: ${endpoint}`);
          return cached;
        }
      }
    }

    // Retry logic
    let lastError;
    for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
      try {
        const response = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
            ...options.headers,
          },
          body: options.body ? JSON.stringify(options.body) : undefined,
          signal: options.signal,
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        const duration = performance.now() - startTime;

        // Cache successful GET responses (but not models status/summary)
        if (method === 'GET' && !endpoint.includes('/models/status') && !endpoint.includes('/models/summary')) {
          this._saveToCache(endpoint, data);
        }

        // Log successful request
        this._logRequest({
          method,
          endpoint,
          status: response.status,
          duration: Math.round(duration),
          timestamp: Date.now(),
        });

        return data;

      } catch (error) {
        lastError = error;
        const errorDetails = {
          attempt,
          maxRetries: this.maxRetries,
          endpoint,
          message: error.message,
          name: error.name,
          stack: error.stack
        };
        
        console.warn(`[APIClient] Attempt ${attempt}/${this.maxRetries} failed for ${endpoint}:`, error.message);
        
        // Log detailed error info for debugging
        if (attempt === this.maxRetries) {
          console.error('[APIClient] All retries exhausted. Error details:', errorDetails);
        }

        if (attempt < this.maxRetries) {
          await this._sleep(this.retryDelay);
        }
      }
    }

    // All retries failed - return fallback data instead of throwing
    const duration = performance.now() - startTime;
    this._logError({
      method,
      endpoint,
      message: lastError?.message || lastError?.toString() || 'Unknown error',
      duration: Math.round(duration),
      timestamp: Date.now(),
    });

    // Return fallback data based on endpoint type
    return this._getFallbackData(endpoint, lastError);
  }

  /**

   * GET request

   */
  async get(endpoint, options = {}) {
    return this.request(endpoint, { ...options, method: 'GET' });
  }

  /**

   * POST request

   */
  async post(endpoint, data, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'POST',
      body: data,
    });
  }

  /**

   * PUT request

   */
  async put(endpoint, data, options = {}) {
    return this.request(endpoint, {
      ...options,
      method: 'PUT',
      body: data,
    });
  }

  /**

   * DELETE request

   */
  async delete(endpoint, options = {}) {
    return this.request(endpoint, { ...options, method: 'DELETE' });
  }

  // ========================================================================
  // CACHE MANAGEMENT
  // ========================================================================

  /**

   * Get data from cache if not expired

   */
  _getFromCache(key) {
    const cacheKey = getCacheKey(key);
    const cached = this.cache.get(cacheKey);

    if (!cached) return null;

    const now = Date.now();
    if (now - cached.timestamp > this.cacheTTL) {
      this.cache.delete(cacheKey);
      return null;
    }

    return cached.data;
  }

  /**

   * Save data to cache with timestamp

   */
  _saveToCache(key, data) {
    const cacheKey = getCacheKey(key);
    this.cache.set(cacheKey, {
      data,
      timestamp: Date.now(),
    });
  }

  /**

   * Clear all cache

   */
  clearCache() {
    this.cache.clear();
    console.log('[APIClient] Cache cleared');
  }

  /**

   * Clear specific cache entry

   */
  clearCacheEntry(key) {
    const cacheKey = getCacheKey(key);
    this.cache.delete(cacheKey);
  }

  // ========================================================================
  // LOGGING
  // ========================================================================

  /**

   * Log successful request

   */
  _logRequest(entry) {
    this.requestLog.unshift(entry);
    if (this.requestLog.length > this.maxLogSize) {
      this.requestLog.pop();
    }
  }

  /**

   * Log error with enhanced details

   */
  _logError(entry) {
    // Add timestamp if not present
    if (!entry.timestamp) {
      entry.timestamp = Date.now();
    }
    
    // Add formatted time for readability
    entry.time = new Date(entry.timestamp).toISOString();
    
    this.errorLog.unshift(entry);
    if (this.errorLog.length > this.maxLogSize) {
      this.errorLog.pop();
    }
    
    // Also log to console for immediate visibility
    console.error('[APIClient] Error logged:', {
      endpoint: entry.endpoint,
      method: entry.method,
      message: entry.message,
      duration: entry.duration
    });
  }

  /**

   * Get request logs

   */
  getRequestLogs(limit = 20) {
    return this.requestLog.slice(0, limit);
  }

  /**

   * Get error logs

   */
  getErrorLogs(limit = 20) {
    return this.errorLog.slice(0, limit);
  }

  // ========================================================================
  // UTILITY
  // ========================================================================

  /**

   * Sleep utility for retry delays

   */
  _sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  /**

   * Get fallback data for failed requests

   * @private

   */
  _getFallbackData(endpoint, error) {
    // Return appropriate fallback based on endpoint
    if (endpoint.includes('/resources/summary')) {
      return {
        success: false,
        error: error.message,
        summary: {
          total_resources: 0,
          free_resources: 0,
          models_available: 0,
          local_routes_count: 0,
          total_api_keys: 0,
          categories: {}
        },
        fallback: true,
        timestamp: new Date().toISOString()
      };
    }
    
    if (endpoint.includes('/models/status')) {
      return {
        success: false,
        error: error.message,
        status: 'error',
        status_message: `Error: ${error.message}`,
        models_loaded: 0,
        models_failed: 0,
        hf_mode: 'unknown',
        transformers_available: false,
        fallback: true,
        timestamp: new Date().toISOString()
      };
    }
    
    if (endpoint.includes('/models/summary')) {
      return {
        ok: false,
        error: error.message,
        summary: {
          total_models: 0,
          loaded_models: 0,
          failed_models: 0,
          hf_mode: 'error',
          transformers_available: false
        },
        categories: {},
        health_registry: [],
        fallback: true,
        timestamp: new Date().toISOString()
      };
    }
    
    if (endpoint.includes('/health') || endpoint.includes('/status')) {
      return {
        status: 'offline',
        healthy: false,
        error: error.message,
        fallback: true,
        timestamp: new Date().toISOString()
      };
    }
    
    // Generic fallback
    return {
      error: error.message,
      fallback: true,
      data: null,
      timestamp: new Date().toISOString()
    };
  }
}

/**

 * Crypto Monitor API Client with pre-configured endpoints

 */
export class CryptoMonitorAPI extends APIClient {
  // ========================================================================
  // HEALTH & STATUS
  // ========================================================================

  async getHealth() {
    return this.get(API_ENDPOINTS.HEALTH);
  }

  async getStatus() {
    return this.get(API_ENDPOINTS.STATUS);
  }

  async getStats() {
    return this.get(API_ENDPOINTS.STATS);
  }

  async getResources() {
    return this.get(API_ENDPOINTS.RESOURCES);
  }

  // ========================================================================
  // MARKET DATA
  // ========================================================================

  async getMarket() {
    return this.get(API_ENDPOINTS.MARKET);
  }

  async getTrending() {
    return this.get(API_ENDPOINTS.TRENDING);
  }

  async getSentiment() {
    return this.get(API_ENDPOINTS.SENTIMENT);
  }

  async getDefi() {
    return this.get(API_ENDPOINTS.DEFI);
  }

  async getTopCoins(limit = 50) {
    return this.get(`${API_ENDPOINTS.COINS_TOP}?limit=${limit}`);
  }

  async getCoinDetails(symbol) {
    return this.get(API_ENDPOINTS.COIN_DETAILS(symbol));
  }

  // ========================================================================
  // CHARTS
  // ========================================================================

  async getPriceChart(symbol, timeframe = '7D') {
    return this.get(`${API_ENDPOINTS.PRICE_CHART(symbol)}?timeframe=${timeframe}`);
  }

  async analyzeChart(symbol, timeframe, indicators) {
    return this.post(API_ENDPOINTS.ANALYZE_CHART, {
      symbol,
      timeframe,
      indicators,
    });
  }

  // ========================================================================
  // NEWS
  // ========================================================================

  async getLatestNews(limit = 40) {
    return this.get(`${API_ENDPOINTS.NEWS_LATEST}?limit=${limit}`);
  }

  async analyzeNews(title, content) {
    return this.post(API_ENDPOINTS.NEWS_ANALYZE, { title, content });
  }

  async summarizeNews(title, content) {
    return this.post(API_ENDPOINTS.NEWS_SUMMARIZE, { title, content });
  }

  // ========================================================================
  // AI/ML MODELS
  // ========================================================================

  async getModelsList() {
    return this.get(API_ENDPOINTS.MODELS_LIST);
  }

  async getModelsStatus() {
    return this.get(API_ENDPOINTS.MODELS_STATUS);
  }

  async getModelsStats() {
    return this.get(API_ENDPOINTS.MODELS_STATS);
  }

  async testModel(modelName, input) {
    return this.post(API_ENDPOINTS.MODELS_TEST, {
      model: modelName,
      input,
    });
  }

  // ========================================================================
  // SENTIMENT ANALYSIS
  // ========================================================================

  async analyzeSentiment(text, mode = 'crypto', model = null) {
    return this.post(API_ENDPOINTS.SENTIMENT_ANALYZE, {
      text,
      mode,
      model,
    });
  }

  async getGlobalSentiment() {
    return this.get(API_ENDPOINTS.SENTIMENT_GLOBAL);
  }

  // ========================================================================
  // AI ADVISOR
  // ========================================================================

  async getAIDecision(symbol, horizon, riskTolerance, context, model) {
    return this.post(API_ENDPOINTS.AI_DECISION, {
      symbol,
      horizon,
      risk_tolerance: riskTolerance,
      context,
      model,
    });
  }

  async getAISignals(symbol) {
    return this.get(`${API_ENDPOINTS.AI_SIGNALS}?symbol=${symbol}`);
  }

  // ========================================================================
  // DATASETS
  // ========================================================================

  async getDatasetsList() {
    return this.get(API_ENDPOINTS.DATASETS_LIST);
  }

  async previewDataset(name, limit = 10) {
    return this.get(`${API_ENDPOINTS.DATASET_PREVIEW(name)}?limit=${limit}`);
  }

  // ========================================================================
  // PROVIDERS
  // ========================================================================

  async getProviders() {
    return this.get(API_ENDPOINTS.PROVIDERS);
  }

  async getProviderDetails(id) {
    return this.get(API_ENDPOINTS.PROVIDER_DETAILS(id));
  }

  async checkProviderHealth(id) {
    return this.get(API_ENDPOINTS.PROVIDER_HEALTH(id));
  }

  async getProvidersConfig() {
    return this.get(API_ENDPOINTS.PROVIDERS_CONFIG);
  }

  // ========================================================================
  // LOGS & DIAGNOSTICS
  // ========================================================================

  async getLogs() {
    return this.get(API_ENDPOINTS.LOGS);
  }

  async getRecentLogs(limit = 50) {
    return this.get(`${API_ENDPOINTS.LOGS_RECENT}?limit=${limit}`);
  }

  async getErrorLogs(limit = 50) {
    return this.get(`${API_ENDPOINTS.LOGS_ERRORS}?limit=${limit}`);
  }

  async clearLogs() {
    return this.delete(API_ENDPOINTS.LOGS_CLEAR);
  }

  // ========================================================================
  // RESOURCES
  // ========================================================================

  async runResourceDiscovery() {
    return this.post(API_ENDPOINTS.RESOURCES_DISCOVERY);
  }

  // ========================================================================
  // HUGGINGFACE INTEGRATION
  // ========================================================================

  async getHFHealth() {
    return this.get(API_ENDPOINTS.HF_HEALTH);
  }

  async runHFSentiment(text) {
    return this.post(API_ENDPOINTS.HF_RUN_SENTIMENT, { text });
  }

  // ========================================================================
  // FEATURE FLAGS
  // ========================================================================

  async getFeatureFlags() {
    return this.get(API_ENDPOINTS.FEATURE_FLAGS);
  }

  async updateFeatureFlag(name, value) {
    return this.put(API_ENDPOINTS.FEATURE_FLAG_UPDATE(name), { value });
  }

  async resetFeatureFlags() {
    return this.post(API_ENDPOINTS.FEATURE_FLAGS_RESET);
  }

  // ========================================================================
  // SETTINGS
  // ========================================================================

  async getSettings() {
    return this.get(API_ENDPOINTS.SETTINGS);
  }

  async saveTokens(tokens) {
    return this.post(API_ENDPOINTS.SETTINGS_TOKENS, tokens);
  }

  async saveTelegramSettings(settings) {
    return this.post(API_ENDPOINTS.SETTINGS_TELEGRAM, settings);
  }

  async saveSignalSettings(settings) {
    return this.post(API_ENDPOINTS.SETTINGS_SIGNALS, settings);
  }

  async saveSchedulingSettings(settings) {
    return this.post(API_ENDPOINTS.SETTINGS_SCHEDULING, settings);
  }

  async saveNotificationSettings(settings) {
    return this.post(API_ENDPOINTS.SETTINGS_NOTIFICATIONS, settings);
  }

  async saveAppearanceSettings(settings) {
    return this.post(API_ENDPOINTS.SETTINGS_APPEARANCE, settings);
  }
}

// ============================================================================
// EXPORT SINGLETON INSTANCE
// ============================================================================

export const api = new CryptoMonitorAPI();
export default api;

/**

 * Export apiClient alias with fetch method for compatibility

 * This allows files to use apiClient.fetch() pattern

 */
export const apiClient = {
  async fetch(url, options = {}) {
    // Convert fetch-style call to api method
    const method = (options.method || 'GET').toUpperCase();
    const endpoint = url.replace(/^.*\/api/, '/api');
    
    try {
      let data;
      if (method === 'GET') {
        data = await api.get(endpoint, { skipCache: options.skipCache, forceRefresh: options.forceRefresh });
      } else if (method === 'POST') {
        const body = options.body ? (typeof options.body === 'string' ? JSON.parse(options.body) : options.body) : {};
        data = await api.post(endpoint, body);
      } else if (method === 'PUT') {
        const body = options.body ? (typeof options.body === 'string' ? JSON.parse(options.body) : options.body) : {};
        data = await api.put(endpoint, body);
      } else if (method === 'DELETE') {
        data = await api.delete(endpoint);
      } else {
        data = await api.get(endpoint);
      }
      
      // Return a Response-like object
      return new Response(JSON.stringify(data), {
        status: 200,
        statusText: 'OK',
        headers: { 'Content-Type': 'application/json' }
      });
    } catch (error) {
      // Return error response
      return new Response(JSON.stringify({ 
        error: error.message || 'Request failed',
        success: false 
      }), {
        status: error.status || 500,
        statusText: error.statusText || 'Internal Server Error',
        headers: { 'Content-Type': 'application/json' }
      });
    }
  }
};

console.log('[APIClient] Initialized (HTTP-only, no WebSocket)');