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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
/**
 * ╔══════════════════════════════════════════════════════════════════════════════╗
 * β•‘                  UNIFIED DATA SERVICE - ENTERPRISE A+                         β•‘
 * β•‘                                                                                β•‘
 * β•‘  Frontend abstraction layer for autonomous backend queries.                   β•‘
 * β•‘  Features:                                                                     β•‘
 * β•‘    β€’ Intelligent query routing via autonomous MCP system                      β•‘
 * β•‘    β€’ Real-time source health monitoring                                        β•‘
 * β•‘    β€’ Automatic retries with exponential backoff                               β•‘
 * β•‘    β€’ Request caching with smart invalidation                                  β•‘
 * β•‘    β€’ WebSocket subscriptions for live updates                                 β•‘
 * β•‘    β€’ Comprehensive telemetry and observability                                β•‘
 * β•‘                                                                                β•‘
 * β•‘  Backend: /api/mcp/autonomous/*                                               β•‘
 * β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
 */

// ═══════════════════════════════════════════════════════════════════════════════
// TYPES & INTERFACES
// ═══════════════════════════════════════════════════════════════════════════════

export interface QueryOptions {
    /** Widget ID for pattern learning */
    widgetId?: string;
    /** Query priority (affects source selection) */
    priority?: 'low' | 'normal' | 'high' | 'critical';
    /** Data freshness requirement */
    freshness?: 'stale' | 'normal' | 'realtime';
    /** Cache TTL in milliseconds (0 = no cache) */
    cacheTtl?: number;
    /** Timeout in milliseconds */
    timeout?: number;
    /** Skip cache and force fresh query */
    skipCache?: boolean;
    /** Abort signal for cancellation */
    signal?: AbortSignal;
}

export interface QueryResult<T = any> {
    data: T;
    source: string;
    latencyMs: number;
    cached: boolean;
    confidence: number;
    timestamp: Date;
}

export interface SourceInfo {
    name: string;
    type: string;
    healthy: boolean;
    latencyMs: number;
    capabilities: string[];
    requestCount?: number;
}

export interface AutonomousStats {
    totalDecisions: number;
    averageConfidence: number;
    averageLatencyMs: number;
    successRate: number;
    topSources: { source: string; count: number; avgLatency: number }[];
    topWidgets: { widget: string; count: number }[];
    queriesLast24h: number;
}

export interface HealthStatus {
    overall: 'healthy' | 'degraded' | 'critical';
    sources: SourceInfo[];
    lastCheck: Date;
}

interface CacheEntry<T> {
    data: T;
    source: string;
    expiresAt: number;
    createdAt: number;
}

type EventCallback = (data: any) => void;

// ═══════════════════════════════════════════════════════════════════════════════
// UNIFIED DATA SERVICE
// ═══════════════════════════════════════════════════════════════════════════════

class UnifiedDataService {
    private baseUrl: string;
    private wsUrl: string;
    private ws: WebSocket | null = null;
    private wsReconnectAttempts = 0;
    private maxWsReconnectAttempts = 10;
    private wsReconnectDelay = 1000;

    private cache = new Map<string, CacheEntry<any>>();
    private pendingRequests = new Map<string, Promise<any>>();
    private eventListeners = new Map<string, Set<EventCallback>>();

    private defaultTimeout = 30000;
    private defaultCacheTtl = 60000; // 1 minute

    // Telemetry
    private queryCount = 0;
    private cacheHits = 0;
    private errorCount = 0;

    constructor() {
        // Auto-detect backend URL
        const isProduction = import.meta.env.PROD;
        const backendPort = import.meta.env.VITE_BACKEND_PORT || '3001';

        if (isProduction) {
            this.baseUrl = '/api/mcp/autonomous';
            this.wsUrl = `wss://${window.location.host}/mcp/ws`;
        } else {
            this.baseUrl = `http://localhost:${backendPort}/api/mcp/autonomous`;
            this.wsUrl = `ws://localhost:${backendPort}/mcp/ws`;
        }

        // Connect WebSocket on init
        this.connectWebSocket();

        // Cleanup stale cache entries periodically
        setInterval(() => this.cleanupCache(), 30000);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // CORE QUERY METHODS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * Query data through the autonomous routing system
     */
    async query<T = any>(
        type: string,
        params: Record<string, any> = {},
        options: QueryOptions = {}
    ): Promise<QueryResult<T>> {
        const {
            widgetId = 'unknown',
            priority = 'normal',
            freshness = 'normal',
            cacheTtl = this.defaultCacheTtl,
            timeout = this.defaultTimeout,
            skipCache = false,
            signal
        } = options;

        this.queryCount++;
        const startTime = Date.now();

        // Generate cache key
        const cacheKey = this.getCacheKey(type, params, widgetId);

        // Check cache (unless skipped or realtime required)
        if (!skipCache && freshness !== 'realtime') {
            const cached = this.getFromCache<T>(cacheKey);
            if (cached) {
                this.cacheHits++;
                return {
                    data: cached.data,
                    source: cached.source + ' (cached)',
                    latencyMs: Date.now() - startTime,
                    cached: true,
                    confidence: 1.0,
                    timestamp: new Date(cached.createdAt)
                };
            }
        }

        // Deduplicate in-flight requests
        const pendingKey = cacheKey;
        if (this.pendingRequests.has(pendingKey)) {
            return this.pendingRequests.get(pendingKey)!;
        }

        // Make the request
        const requestPromise = this.executeQuery<T>(
            type,
            params,
            { widgetId, priority, freshness, timeout, signal }
        ).then(result => {
            // Cache successful results
            if (cacheTtl > 0) {
                this.setCache(cacheKey, result.data, result.source, cacheTtl);
            }
            return result;
        }).finally(() => {
            this.pendingRequests.delete(pendingKey);
        });

        this.pendingRequests.set(pendingKey, requestPromise);
        return requestPromise;
    }

    /**
     * Execute the actual query with retries
     */
    private async executeQuery<T>(
        type: string,
        params: Record<string, any>,
        options: {
            widgetId: string;
            priority: string;
            freshness: string;
            timeout: number;
            signal?: AbortSignal;
        }
    ): Promise<QueryResult<T>> {
        const startTime = Date.now();
        const maxRetries = options.priority === 'critical' ? 3 : 1;
        let lastError: Error | null = null;

        for (let attempt = 0; attempt <= maxRetries; attempt++) {
            try {
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), options.timeout);

                // Combine external signal with timeout
                if (options.signal) {
                    options.signal.addEventListener('abort', () => controller.abort());
                }

                const response = await fetch(`${this.baseUrl}/query`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        type,
                        params,
                        widgetId: options.widgetId,
                        priority: options.priority,
                        freshness: options.freshness
                    }),
                    signal: controller.signal
                });

                clearTimeout(timeoutId);

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error || `HTTP ${response.status}`);
                }

                const result = await response.json();

                return {
                    data: result.data as T,
                    source: result.meta?.source || 'unknown',
                    latencyMs: Date.now() - startTime,
                    cached: false,
                    confidence: result.meta?.confidence || 1.0,
                    timestamp: new Date()
                };

            } catch (error: any) {
                lastError = error;
                this.errorCount++;

                // Don't retry on abort
                if (error.name === 'AbortError') {
                    throw new Error('Query cancelled or timed out');
                }

                // Exponential backoff before retry
                if (attempt < maxRetries) {
                    await this.sleep(Math.pow(2, attempt) * 500);
                }
            }
        }

        throw lastError || new Error('Query failed after retries');
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // CONVENIENCE METHODS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * Fetch a list of items
     */
    async list<T = any>(
        domain: string,
        options: QueryOptions = {}
    ): Promise<T[]> {
        const result = await this.query<T[]>(`${domain}.list`, {}, options);
        return result.data;
    }

    /**
     * Fetch a single item by ID
     */
    async get<T = any>(
        domain: string,
        id: string,
        options: QueryOptions = {}
    ): Promise<T> {
        const result = await this.query<T>(`${domain}.get`, { id }, options);
        return result.data;
    }

    /**
     * Search with a query string
     */
    async search<T = any>(
        domain: string,
        query: string,
        options: QueryOptions = {}
    ): Promise<T[]> {
        const result = await this.query<T[]>(
            `${domain}.search`,
            { query },
            { ...options, priority: 'high' }
        );
        return result.data;
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // MONITORING & STATUS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * Get available data sources and their health
     */
    async getSources(): Promise<SourceInfo[]> {
        try {
            const response = await fetch(`${this.baseUrl}/sources`);
            if (!response.ok) throw new Error('Failed to fetch sources');

            const data = await response.json();
            return data.sources || [];
        } catch (error) {
            console.error('Failed to fetch sources:', error);
            return [];
        }
    }

    /**
     * Get autonomous system statistics
     */
    async getStats(): Promise<AutonomousStats> {
        try {
            const response = await fetch(`${this.baseUrl}/stats`);
            if (!response.ok) throw new Error('Failed to fetch stats');

            return await response.json();
        } catch (error) {
            console.error('Failed to fetch stats:', error);
            return {
                totalDecisions: 0,
                averageConfidence: 0,
                averageLatencyMs: 0,
                successRate: 0,
                topSources: [],
                topWidgets: [],
                queriesLast24h: 0
            };
        }
    }

    /**
     * Get overall system health
     */
    async getHealth(): Promise<HealthStatus> {
        const sources = await this.getSources();

        const healthySources = sources.filter(s => s.healthy).length;
        const totalSources = sources.length;

        let overall: HealthStatus['overall'] = 'healthy';
        if (totalSources > 0) {
            const ratio = healthySources / totalSources;
            if (ratio < 0.5) overall = 'critical';
            else if (ratio < 0.8) overall = 'degraded';
        }

        return {
            overall,
            sources,
            lastCheck: new Date()
        };
    }

    /**
     * Get decision history
     */
    async getDecisions(limit: number = 50): Promise<any[]> {
        try {
            const response = await fetch(`${this.baseUrl}/decisions?limit=${limit}`);
            if (!response.ok) throw new Error('Failed to fetch decisions');

            const data = await response.json();
            return data.decisions || [];
        } catch (error) {
            console.error('Failed to fetch decisions:', error);
            return [];
        }
    }

    /**
     * Get learned patterns for a widget
     */
    async getPatterns(widgetId: string): Promise<any> {
        try {
            const response = await fetch(`${this.baseUrl}/patterns?widgetId=${widgetId}`);
            if (!response.ok) throw new Error('Failed to fetch patterns');

            return await response.json();
        } catch (error) {
            console.error('Failed to fetch patterns:', error);
            return null;
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // WEBSOCKET SUBSCRIPTIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * Subscribe to real-time events
     */
    subscribe(eventType: string, callback: EventCallback): () => void {
        if (!this.eventListeners.has(eventType)) {
            this.eventListeners.set(eventType, new Set());
        }
        this.eventListeners.get(eventType)!.add(callback);

        // Return unsubscribe function
        return () => {
            const listeners = this.eventListeners.get(eventType);
            if (listeners) {
                listeners.delete(callback);
            }
        };
    }

    /**
     * Subscribe to source health changes
     */
    onSourceHealthChange(callback: (sources: SourceInfo[]) => void): () => void {
        return this.subscribe('source:health', callback);
    }

    /**
     * Subscribe to pattern updates
     */
    onPatternRecorded(callback: (pattern: any) => void): () => void {
        return this.subscribe('pattern:recorded', callback);
    }

    /**
     * Subscribe to failure events
     */
    onFailure(callback: (failure: any) => void): () => void {
        return this.subscribe('failure:recorded', callback);
    }

    /**
     * Connect WebSocket
     */
    private connectWebSocket(): void {
        if (this.ws?.readyState === WebSocket.OPEN) return;

        try {
            this.ws = new WebSocket(this.wsUrl);

            this.ws.onopen = () => {
                console.log('πŸ”Œ UnifiedDataService WebSocket connected');
                this.wsReconnectAttempts = 0;
                this.wsReconnectDelay = 1000;

                // Subscribe to autonomous events
                this.ws?.send(JSON.stringify({
                    type: 'subscribe',
                    topics: ['pattern:*', 'failure:*', 'source:*', 'decision:*']
                }));
            };

            this.ws.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    this.handleWebSocketMessage(message);
                } catch (error) {
                    console.warn('Failed to parse WebSocket message:', error);
                }
            };

            this.ws.onerror = (error) => {
                console.warn('WebSocket error:', error);
            };

            this.ws.onclose = () => {
                console.log('WebSocket closed, attempting reconnect...');
                this.scheduleReconnect();
            };

        } catch (error) {
            console.warn('Failed to connect WebSocket:', error);
            this.scheduleReconnect();
        }
    }

    /**
     * Handle incoming WebSocket message
     */
    private handleWebSocketMessage(message: any): void {
        const { type, data } = message;

        // Emit to listeners
        const listeners = this.eventListeners.get(type);
        if (listeners) {
            listeners.forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.warn('Event listener error:', error);
                }
            });
        }

        // Also emit to wildcard listeners
        const wildcardType = type.split(':')[0] + ':*';
        const wildcardListeners = this.eventListeners.get(wildcardType);
        if (wildcardListeners) {
            wildcardListeners.forEach(callback => {
                try {
                    callback({ type, data });
                } catch (error) {
                    console.warn('Wildcard listener error:', error);
                }
            });
        }
    }

    /**
     * Schedule WebSocket reconnection
     */
    private scheduleReconnect(): void {
        if (this.wsReconnectAttempts >= this.maxWsReconnectAttempts) {
            console.error('Max WebSocket reconnect attempts reached');
            return;
        }

        this.wsReconnectAttempts++;
        this.wsReconnectDelay = Math.min(this.wsReconnectDelay * 1.5, 30000);

        setTimeout(() => {
            this.connectWebSocket();
        }, this.wsReconnectDelay);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // CACHE MANAGEMENT
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * Generate cache key
     */
    private getCacheKey(type: string, params: any, widgetId: string): string {
        return `${widgetId}:${type}:${JSON.stringify(params)}`;
    }

    /**
     * Get item from cache
     */
    private getFromCache<T>(key: string): CacheEntry<T> | null {
        const entry = this.cache.get(key);
        if (!entry) return null;

        if (Date.now() > entry.expiresAt) {
            this.cache.delete(key);
            return null;
        }

        return entry as CacheEntry<T>;
    }

    /**
     * Set item in cache
     */
    private setCache(key: string, data: any, source: string, ttl: number): void {
        this.cache.set(key, {
            data,
            source,
            expiresAt: Date.now() + ttl,
            createdAt: Date.now()
        });
    }

    /**
     * Invalidate cache for a pattern
     */
    invalidateCache(pattern?: string): void {
        if (!pattern) {
            this.cache.clear();
            return;
        }

        for (const key of this.cache.keys()) {
            if (key.includes(pattern)) {
                this.cache.delete(key);
            }
        }
    }

    /**
     * Cleanup expired cache entries
     */
    private cleanupCache(): void {
        const now = Date.now();
        for (const [key, entry] of this.cache.entries()) {
            if (now > entry.expiresAt) {
                this.cache.delete(key);
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // TELEMETRY
    // ═══════════════════════════════════════════════════════════════════════════

    /**
     * Get service telemetry
     */
    getTelemetry() {
        return {
            queryCount: this.queryCount,
            cacheHits: this.cacheHits,
            cacheSize: this.cache.size,
            errorCount: this.errorCount,
            cacheHitRate: this.queryCount > 0
                ? (this.cacheHits / this.queryCount * 100).toFixed(1) + '%'
                : '0%',
            wsConnected: this.ws?.readyState === WebSocket.OPEN
        };
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // UTILITIES
    // ═══════════════════════════════════════════════════════════════════════════

    private sleep(ms: number): Promise<void> {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    /**
     * Disconnect and cleanup
     */
    disconnect(): void {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        this.cache.clear();
        this.eventListeners.clear();
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SINGLETON EXPORT
// ═══════════════════════════════════════════════════════════════════════════════

export const dataService = new UnifiedDataService();
export const unifiedDataService = dataService;

// Also export the class for testing
export { UnifiedDataService };