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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
/**

 * ============================================

 * PROVIDER AUTO-DISCOVERY ENGINE

 * Enterprise Edition - Crypto Monitor Ultimate

 * ============================================

 *

 * Automatically discovers and manages 200+ API providers

 * Features:

 * - Auto-loads providers from JSON config

 * - Categorizes providers (market, exchange, defi, news, etc.)

 * - Health checking & status monitoring

 * - Dynamic UI injection

 * - Search & filtering

 * - Rate limit tracking

 */

class ProviderDiscoveryEngine {
    constructor() {
        this.providers = [];
        this.categories = new Map();
        this.healthStatus = new Map();
        this.configPath = '/static/providers_config_ultimate.json'; // Fallback path (prefer /api/providers/config)
        this.initialized = false;
    }

    /**

     * Initialize the discovery engine

     */
    async init() {
        if (this.initialized) return;

        // Don't log initialization - only log if providers are successfully loaded
        try {
            // Try to load from backend API first
            await this.loadProvidersFromAPI();
        } catch (error) {
            // Silently fallback to JSON file - providers are optional
            await this.loadProvidersFromJSON();
        }

        this.categorizeProviders();
        this.startHealthMonitoring();

        this.initialized = true;
        // Only log if providers were successfully loaded
        if (this.providers.length > 0) {
            console.log(`[Provider Discovery] Initialized with ${this.providers.length} providers in ${this.categories.size} categories`);
        }
        // Silently skip if no providers loaded - they're optional
    }

    /**

     * Load providers from backend API

     */
    async loadProvidersFromAPI() {
        try {
            // Try the new /api/providers/config endpoint first
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);
            
            let response = null;
            try {
                response = await fetch('/api/providers/config', {
                    signal: controller.signal
                });
            } catch (fetchError) {
                // Completely suppress fetch errors - providers are optional
                clearTimeout(timeoutId);
                throw new Error('Network error');
            }
            clearTimeout(timeoutId);
            
            if (!response || !response.ok) {
                throw new Error(`HTTP ${response?.status || 'network error'}`);
            }

            try {
                const data = await response.json();
                this.processProviderData(data);
            } catch (jsonError) {
                // Silently handle JSON parse errors
                throw new Error('Invalid response');
            }
        } catch (error) {
            // Silently fail - will fallback to JSON
            throw error;
        }
    }

    /**

     * Load providers from JSON file

     */
    async loadProvidersFromJSON() {
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);
            
            let response = null;
            try {
                response = await fetch(this.configPath, {
                    signal: controller.signal
                });
            } catch (fetchError) {
                // Completely suppress fetch errors - providers are optional
                clearTimeout(timeoutId);
                this.useFallbackConfig();
                return;
            }
            clearTimeout(timeoutId);
            
            if (!response || !response.ok) {
                // Silently use fallback config
                this.useFallbackConfig();
                return;
            }

            try {
                const data = await response.json();
                this.processProviderData(data);
            } catch (jsonError) {
                // Silently use fallback config on parse errors
                this.useFallbackConfig();
            }
        } catch (error) {
            // Completely silent - use fallback config
            this.useFallbackConfig();
        }
    }

    /**

     * Process provider data from any source

     */
    processProviderData(data) {
        if (!data || !data.providers) {
            throw new Error('Invalid provider data structure');
        }

        // Convert object to array
        this.providers = Object.entries(data.providers).map(([id, provider]) => ({
            id,
            ...provider,
            status: 'unknown',
            lastCheck: null,
            responseTime: null
        }));

        // Only log if providers were successfully loaded
        if (this.providers.length > 0) {
            console.log(`[Provider Discovery] Loaded ${this.providers.length} providers`);
        }
    }

    /**

     * Categorize providers

     */
    categorizeProviders() {
        this.categories.clear();

        this.providers.forEach(provider => {
            const category = provider.category || 'other';

            if (!this.categories.has(category)) {
                this.categories.set(category, []);
            }

            this.categories.get(category).push(provider);
        });

        // Sort providers within each category by priority
        this.categories.forEach((providers, category) => {
            providers.sort((a, b) => (b.priority || 0) - (a.priority || 0));
        });

        // Only log if categories were created
        if (this.categories.size > 0) {
            console.log(`[Provider Discovery] Categorized into: ${Array.from(this.categories.keys()).join(', ')}`);
        }
    }

    /**

     * Get all providers

     */
    getAllProviders() {
        return this.providers;
    }

    /**

     * Get providers by category

     */
    getProvidersByCategory(category) {
        return this.categories.get(category) || [];
    }

    /**

     * Get all categories

     */
    getCategories() {
        return Array.from(this.categories.keys());
    }

    /**

     * Search providers

     */
    searchProviders(query) {
        const lowerQuery = query.toLowerCase();
        return this.providers.filter(provider =>
            provider.name.toLowerCase().includes(lowerQuery) ||
            provider.id.toLowerCase().includes(lowerQuery) ||
            (provider.category || '').toLowerCase().includes(lowerQuery)
        );
    }

    /**

     * Filter providers

     */
    filterProviders(filters = {}) {
        let filtered = [...this.providers];

        if (filters.category) {
            filtered = filtered.filter(p => p.category === filters.category);
        }

        if (filters.free !== undefined) {
            filtered = filtered.filter(p => p.free === filters.free);
        }

        if (filters.requiresAuth !== undefined) {
            filtered = filtered.filter(p => p.requires_auth === filters.requiresAuth);
        }

        if (filters.status) {
            filtered = filtered.filter(p => p.status === filters.status);
        }

        return filtered;
    }

    /**

     * Get provider statistics

     */
    getStats() {
        const total = this.providers.length;
        const free = this.providers.filter(p => p.free).length;
        const paid = total - free;
        const requiresAuth = this.providers.filter(p => p.requires_auth).length;

        const statuses = {
            online: this.providers.filter(p => p.status === 'online').length,
            offline: this.providers.filter(p => p.status === 'offline').length,
            unknown: this.providers.filter(p => p.status === 'unknown').length
        };

        return {
            total,
            free,
            paid,
            requiresAuth,
            categories: this.categories.size,
            statuses
        };
    }

    /**

     * Health check for a single provider

     */
    async checkProviderHealth(providerId) {
        const provider = this.providers.find(p => p.id === providerId);
        if (!provider) return null;

        const startTime = Date.now();

        try {
            // Call backend health check endpoint with timeout and silent error handling
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 5000);
            
            let response = null;
            try {
                response = await fetch(`/api/providers/${providerId}/health`, {
                    signal: controller.signal
                });
            } catch (fetchError) {
                // Completely suppress fetch errors - health checks are optional
                clearTimeout(timeoutId);
                provider.status = 'unknown';
                provider.lastCheck = new Date();
                provider.responseTime = null;
                return { status: 'unknown' };
            }
            clearTimeout(timeoutId);

            const responseTime = Date.now() - startTime;
            const status = response && response.ok ? 'online' : 'unknown';

            // Update provider status
            provider.status = status;
            provider.lastCheck = new Date();
            provider.responseTime = responseTime;

            this.healthStatus.set(providerId, {
                status,
                lastCheck: provider.lastCheck,
                responseTime
            });

            return { status, responseTime };
        } catch (error) {
            // Silently mark as unknown on any error
            provider.status = 'unknown';
            provider.lastCheck = new Date();
            provider.responseTime = null;

            this.healthStatus.set(providerId, {
                status: 'unknown',
                lastCheck: provider.lastCheck
            });

            return { status: 'unknown' };
        }
    }

    /**

     * Start health monitoring (periodic checks)

     */
    startHealthMonitoring(interval = 60000) {
        // Check a few high-priority providers periodically
        setInterval(async () => {
            const highPriorityProviders = this.providers
                .filter(p => (p.priority || 0) >= 8)
                .slice(0, 5);

            for (const provider of highPriorityProviders) {
                await this.checkProviderHealth(provider.id);
            }

            // Silently complete health checks - don't log unless there's an issue
            // Only log if providers are actually being monitored
            if (highPriorityProviders.length > 0) {
                // Health checks are running silently - no log needed
            }
        }, interval);
    }

    /**

     * Generate provider card HTML

     */
    generateProviderCard(provider) {
        const statusColors = {
            online: 'var(--color-accent-green)',
            offline: 'var(--color-accent-red)',
            unknown: 'var(--color-text-secondary)'
        };

        const statusColor = statusColors[provider.status] || statusColors.unknown;
        const icon = this.getCategoryIcon(provider.category);

        return `

            <div class="provider-card glass-effect" data-provider-id="${provider.id}">

                <div class="provider-card-header">

                    <div class="provider-icon">

                        ${window.getIcon ? window.getIcon(icon, 32) : ''}

                    </div>

                    <div class="provider-info">

                        <h3 class="provider-name">${provider.name}</h3>

                        <span class="provider-category">${this.formatCategory(provider.category)}</span>

                    </div>

                    <div class="provider-status" style="color: ${statusColor}">

                        <span class="status-dot" style="background: ${statusColor}"></span>

                        ${provider.status}

                    </div>

                </div>



                <div class="provider-card-body">

                    <div class="provider-meta">

                        <div class="meta-item">

                            <span class="meta-label">Type:</span>

                            <span class="meta-value">${provider.free ? 'Free' : 'Paid'}</span>

                        </div>

                        <div class="meta-item">

                            <span class="meta-label">Auth:</span>

                            <span class="meta-value">${provider.requires_auth ? 'Required' : 'No'}</span>

                        </div>

                        <div class="meta-item">

                            <span class="meta-label">Priority:</span>

                            <span class="meta-value">${provider.priority || 'N/A'}/10</span>

                        </div>

                    </div>



                    ${this.generateRateLimitInfo(provider)}



                    <div class="provider-actions">

                        <button class="btn-secondary btn-sm" onclick="providerDiscovery.checkProviderHealth('${provider.id}')">

                            ${window.getIcon ? window.getIcon('refresh', 16) : ''} Test

                        </button>

                        ${provider.docs_url ? `

                            <a href="${provider.docs_url}" target="_blank" class="btn-secondary btn-sm">

                                ${window.getIcon ? window.getIcon('fileText', 16) : ''} Docs

                            </a>

                        ` : ''}

                    </div>

                </div>

            </div>

        `;
    }

    /**

     * Generate rate limit information

     */
    generateRateLimitInfo(provider) {
        if (!provider.rate_limit) return '';

        const limits = [];
        if (provider.rate_limit.requests_per_second) {
            limits.push(`${provider.rate_limit.requests_per_second}/sec`);
        }
        if (provider.rate_limit.requests_per_minute) {
            limits.push(`${provider.rate_limit.requests_per_minute}/min`);
        }
        if (provider.rate_limit.requests_per_hour) {
            limits.push(`${provider.rate_limit.requests_per_hour}/hr`);
        }
        if (provider.rate_limit.requests_per_day) {
            limits.push(`${provider.rate_limit.requests_per_day}/day`);
        }

        if (limits.length === 0) return '';

        return `

            <div class="provider-rate-limit">

                <span class="rate-limit-label">Rate Limit:</span>

                <span class="rate-limit-value">${limits.join(', ')}</span>

            </div>

        `;
    }

    /**

     * Get icon for category

     */
    getCategoryIcon(category) {
        const icons = {
            market_data: 'barChart',
            exchange: 'activity',
            blockchain_explorer: 'database',
            defi: 'layers',
            sentiment: 'activity',
            news: 'newspaper',
            social: 'users',
            rpc: 'server',
            analytics: 'pieChart',
            whale_tracking: 'trendingUp',
            ml_model: 'brain'
        };

        return icons[category] || 'globe';
    }

    /**

     * Format category name

     */
    formatCategory(category) {
        if (!category) return 'Other';
        return category.split('_').map(word =>
            word.charAt(0).toUpperCase() + word.slice(1)
        ).join(' ');
    }

    /**

     * Render providers in container

     */
    renderProviders(containerId, options = {}) {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Container "${containerId}" not found`);
            return;
        }

        let providers = this.providers;

        // Apply filters
        if (options.category) {
            providers = this.getProvidersByCategory(options.category);
        }
        if (options.search) {
            providers = this.searchProviders(options.search);
        }
        if (options.filters) {
            providers = this.filterProviders(options.filters);
        }

        // Sort
        if (options.sortBy) {
            providers = [...providers].sort((a, b) => {
                if (options.sortBy === 'name') {
                    return a.name.localeCompare(b.name);
                }
                if (options.sortBy === 'priority') {
                    return (b.priority || 0) - (a.priority || 0);
                }
                return 0;
            });
        }

        // Limit
        if (options.limit) {
            providers = providers.slice(0, options.limit);
        }

        // Generate HTML
        const html = providers.map(p => this.generateProviderCard(p)).join('');
        container.innerHTML = html;

        // Only log if providers were actually rendered
        if (providers.length > 0) {
            console.log(`[Provider Discovery] Rendered ${providers.length} providers`);
        }
    }

    /**

     * Render category tabs

     */
    renderCategoryTabs(containerId) {
        const container = document.getElementById(containerId);
        if (!container) return;

        const categories = this.getCategories();
        const html = categories.map(category => {
            const count = this.getProvidersByCategory(category).length;
            return `

                <button class="category-tab" data-category="${category}">

                    ${window.getIcon ? window.getIcon(this.getCategoryIcon(category), 20) : ''}

                    <span>${this.formatCategory(category)}</span>

                    <span class="category-count">${count}</span>

                </button>

            `;
        }).join('');

        container.innerHTML = html;
    }

    /**

     * Use fallback minimal config

     */
    useFallbackConfig() {
        // Silently use fallback config - providers are optional
        this.providers = [
            {
                id: 'coingecko',
                name: 'CoinGecko',
                category: 'market_data',
                free: true,
                requires_auth: false,
                priority: 10,
                status: 'unknown'
            },
            {
                id: 'binance',
                name: 'Binance',
                category: 'exchange',
                free: true,
                requires_auth: false,
                priority: 10,
                status: 'unknown'
            }
        ];
    }
}

// Export singleton instance
window.providerDiscovery = new ProviderDiscoveryEngine();

// Silently load engine - only log if providers are successfully initialized