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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
"""

Comprehensive monitoring and logging system for MCP AI Data Scientist.

Provides centralized logging, metrics collection, and system health monitoring.

"""

import logging
import time
import json
import asyncio
from datetime import datetime, timezone

# Optional dependency
try:
    import psutil
    PSUTIL_AVAILABLE = True
except ImportError:
    PSUTIL_AVAILABLE = False
from typing import Dict, Any, Optional, List, Callable
from pathlib import Path
from dataclasses import dataclass, asdict
from contextlib import asynccontextmanager
import threading
from collections import defaultdict, deque

from .config import settings


@dataclass
class MetricPoint:
    """Individual metric data point."""
    name: str
    value: float
    timestamp: datetime
    tags: Dict[str, str] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for serialization."""
        return {
            "name": self.name,
            "value": self.value,
            "timestamp": self.timestamp.isoformat(),
            "tags": self.tags or {}
        }


@dataclass
class HealthStatus:
    """System health status."""
    component: str
    is_healthy: bool
    status_message: str
    last_check: datetime
    metrics: Dict[str, float] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for serialization."""
        return {
            "component": self.component,
            "is_healthy": self.is_healthy,
            "status_message": self.status_message,
            "last_check": self.last_check.isoformat(),
            "metrics": self.metrics or {}
        }


class MetricsCollector:
    """Collects and stores system metrics."""
    
    def __init__(self, max_points: int = 10000):
        self.max_points = max_points
        self.metrics: Dict[str, deque] = defaultdict(lambda: deque(maxlen=max_points))
        self.lock = threading.Lock()
    
    def record_metric(self, name: str, value: float, tags: Dict[str, str] = None):
        """Record a metric point."""
        point = MetricPoint(
            name=name,
            value=value,
            timestamp=datetime.now(timezone.utc),
            tags=tags
        )
        
        with self.lock:
            self.metrics[name].append(point)
    
    def get_metrics(self, name: str, limit: int = 100) -> List[MetricPoint]:
        """Get recent metrics for a given name."""
        with self.lock:
            if name in self.metrics:
                return list(self.metrics[name])[-limit:]
            return []
    
    def get_all_metrics(self) -> Dict[str, List[Dict[str, Any]]]:
        """Get all metrics as serializable dictionary."""
        with self.lock:
            return {
                name: [point.to_dict() for point in points]
                for name, points in self.metrics.items()
            }
    
    def get_latest_values(self) -> Dict[str, float]:
        """Get latest value for each metric."""
        with self.lock:
            return {
                name: points[-1].value if points else 0.0
                for name, points in self.metrics.items()
            }


class PerformanceMonitor:
    """Monitors system performance metrics."""
    
    def __init__(self, metrics_collector: MetricsCollector):
        self.metrics = metrics_collector
        self.monitoring = False
        self.monitor_task = None
        self.process = psutil.Process() if PSUTIL_AVAILABLE else None
    
    async def start_monitoring(self, interval: float = 30.0):
        """Start performance monitoring."""
        if self.monitoring:
            return
        
        self.monitoring = True
        self.monitor_task = asyncio.create_task(self._monitor_loop(interval))
    
    async def stop_monitoring(self):
        """Stop performance monitoring."""
        self.monitoring = False
        if self.monitor_task:
            self.monitor_task.cancel()
            try:
                await self.monitor_task
            except asyncio.CancelledError:
                pass
    
    async def _monitor_loop(self, interval: float):
        """Main monitoring loop."""
        while self.monitoring:
            try:
                await self._collect_system_metrics()
                await asyncio.sleep(interval)
            except asyncio.CancelledError:
                break
            except Exception as e:
                logging.error(f"Error in performance monitoring: {e}")
                await asyncio.sleep(interval)
    
    async def _collect_system_metrics(self):
        """Collect system performance metrics."""
        try:
            if not PSUTIL_AVAILABLE:
                # Record placeholder metrics when psutil is not available
                self.metrics.record_metric("system.cpu_percent", 0.0)
                self.metrics.record_metric("system.memory_rss_mb", 0.0)
                return
            
            # CPU metrics
            cpu_percent = self.process.cpu_percent()
            self.metrics.record_metric("system.cpu_percent", cpu_percent)
            
            # Memory metrics
            memory_info = self.process.memory_info()
            self.metrics.record_metric("system.memory_rss_mb", memory_info.rss / 1024 / 1024)
            self.metrics.record_metric("system.memory_vms_mb", memory_info.vms / 1024 / 1024)
            
            # System-wide metrics
            system_cpu = psutil.cpu_percent()
            system_memory = psutil.virtual_memory()
            
            self.metrics.record_metric("system.total_cpu_percent", system_cpu)
            self.metrics.record_metric("system.total_memory_percent", system_memory.percent)
            self.metrics.record_metric("system.available_memory_gb", system_memory.available / 1024 / 1024 / 1024)
            
            # Disk usage
            disk_usage = psutil.disk_usage('/')
            self.metrics.record_metric("system.disk_usage_percent", 
                                     (disk_usage.used / disk_usage.total) * 100)
            
            # Network I/O (if available)
            try:
                net_io = psutil.net_io_counters()
                self.metrics.record_metric("system.network_bytes_sent", net_io.bytes_sent)
                self.metrics.record_metric("system.network_bytes_recv", net_io.bytes_recv)
            except:
                pass  # Network metrics not available on all systems
            
        except Exception as e:
            logging.error(f"Error collecting system metrics: {e}")


class ApplicationMonitor:
    """Monitors application-specific metrics."""
    
    def __init__(self, metrics_collector: MetricsCollector):
        self.metrics = metrics_collector
        self.request_counts = defaultdict(int)
        self.error_counts = defaultdict(int)
        self.response_times = defaultdict(list)
    
    def record_request(self, endpoint: str, method: str = "GET"):
        """Record an API request."""
        key = f"{method}:{endpoint}"
        self.request_counts[key] += 1
        self.metrics.record_metric(
            "app.requests_total",
            self.request_counts[key],
            tags={"endpoint": endpoint, "method": method}
        )
    
    def record_error(self, endpoint: str, error_type: str, method: str = "GET"):
        """Record an application error."""
        key = f"{method}:{endpoint}:{error_type}"
        self.error_counts[key] += 1
        self.metrics.record_metric(
            "app.errors_total",
            self.error_counts[key],
            tags={"endpoint": endpoint, "method": method, "error_type": error_type}
        )
    
    @asynccontextmanager
    async def time_operation(self, operation_name: str, tags: Dict[str, str] = None):
        """Context manager to time operations."""
        start_time = time.time()
        try:
            yield
        finally:
            duration = time.time() - start_time
            self.metrics.record_metric(
                f"app.operation_duration_seconds",
                duration,
                tags={**(tags or {}), "operation": operation_name}
            )
    
    def record_analysis_stage(self, stage: str, duration: float, success: bool):
        """Record analysis stage metrics."""
        self.metrics.record_metric(
            "app.analysis_stage_duration_seconds",
            duration,
            tags={"stage": stage, "success": str(success)}
        )
        
        self.metrics.record_metric(
            "app.analysis_stage_count",
            1,
            tags={"stage": stage, "success": str(success)}
        )
    
    def record_mcp_call(self, server: str, tool: str, duration: float, success: bool):
        """Record MCP server call metrics."""
        self.metrics.record_metric(
            "app.mcp_call_duration_seconds",
            duration,
            tags={"server": server, "tool": tool, "success": str(success)}
        )
        
        self.metrics.record_metric(
            "app.mcp_call_count",
            1,
            tags={"server": server, "tool": tool, "success": str(success)}
        )


class HealthChecker:
    """Performs health checks on system components."""
    
    def __init__(self):
        self.health_status: Dict[str, HealthStatus] = {}
        self.health_checks: Dict[str, Callable] = {}
    
    def register_health_check(self, component: str, check_func: Callable):
        """Register a health check function for a component."""
        self.health_checks[component] = check_func
    
    async def check_component_health(self, component: str) -> HealthStatus:
        """Check health of a specific component."""
        if component not in self.health_checks:
            return HealthStatus(
                component=component,
                is_healthy=False,
                status_message="No health check registered",
                last_check=datetime.now(timezone.utc)
            )
        
        try:
            check_func = self.health_checks[component]
            if asyncio.iscoroutinefunction(check_func):
                result = await check_func()
            else:
                result = check_func()
            
            if isinstance(result, bool):
                status = HealthStatus(
                    component=component,
                    is_healthy=result,
                    status_message="OK" if result else "Health check failed",
                    last_check=datetime.now(timezone.utc)
                )
            elif isinstance(result, dict):
                status = HealthStatus(
                    component=component,
                    is_healthy=result.get("healthy", False),
                    status_message=result.get("message", "Unknown"),
                    last_check=datetime.now(timezone.utc),
                    metrics=result.get("metrics", {})
                )
            else:
                status = HealthStatus(
                    component=component,
                    is_healthy=False,
                    status_message=f"Invalid health check result: {result}",
                    last_check=datetime.now(timezone.utc)
                )
            
        except Exception as e:
            status = HealthStatus(
                component=component,
                is_healthy=False,
                status_message=f"Health check error: {str(e)}",
                last_check=datetime.now(timezone.utc)
            )
        
        self.health_status[component] = status
        return status
    
    async def check_all_health(self) -> Dict[str, HealthStatus]:
        """Check health of all registered components."""
        tasks = [
            self.check_component_health(component)
            for component in self.health_checks.keys()
        ]
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        
        health_results = {}
        for i, (component, result) in enumerate(zip(self.health_checks.keys(), results)):
            if isinstance(result, Exception):
                health_results[component] = HealthStatus(
                    component=component,
                    is_healthy=False,
                    status_message=f"Health check exception: {str(result)}",
                    last_check=datetime.now(timezone.utc)
                )
            else:
                health_results[component] = result
        
        self.health_status.update(health_results)
        return health_results
    
    def get_overall_health(self) -> bool:
        """Get overall system health status."""
        if not self.health_status:
            return False
        
        return all(status.is_healthy for status in self.health_status.values())


class MonitoringSystem:
    """Central monitoring system that coordinates all monitoring components."""
    
    def __init__(self):
        self.metrics_collector = MetricsCollector()
        self.performance_monitor = PerformanceMonitor(self.metrics_collector)
        self.app_monitor = ApplicationMonitor(self.metrics_collector)
        self.health_checker = HealthChecker()
        
        # Setup logging
        self.logger = self._setup_logging()
        
        # Monitoring state
        self.monitoring_active = False
    
    def _setup_logging(self) -> logging.Logger:
        """Setup centralized logging."""
        logger = logging.getLogger("mcp_data_scientist")
        
        if not logger.handlers:
            # Create formatter
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            )
            
            # File handler
            log_file = Path(settings.log_file)
            log_file.parent.mkdir(parents=True, exist_ok=True)
            
            file_handler = logging.FileHandler(log_file)
            file_handler.setFormatter(formatter)
            file_handler.setLevel(getattr(logging, settings.log_level.upper()))
            
            # Console handler
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(formatter)
            console_handler.setLevel(logging.INFO)
            
            # Add handlers
            logger.addHandler(file_handler)
            logger.addHandler(console_handler)
            logger.setLevel(logging.DEBUG)
        
        return logger
    
    async def start_monitoring(self):
        """Start all monitoring components."""
        if self.monitoring_active:
            return
        
        self.logger.info("Starting monitoring system...")
        
        # Start performance monitoring
        await self.performance_monitor.start_monitoring()
        
        # Register default health checks
        self._register_default_health_checks()
        
        self.monitoring_active = True
        self.logger.info("Monitoring system started successfully")
    
    async def stop_monitoring(self):
        """Stop all monitoring components."""
        if not self.monitoring_active:
            return
        
        self.logger.info("Stopping monitoring system...")
        
        # Stop performance monitoring
        await self.performance_monitor.stop_monitoring()
        
        self.monitoring_active = False
        self.logger.info("Monitoring system stopped")
    
    def _register_default_health_checks(self):
        """Register default health checks."""
        
        def database_health_check():
            """Check database connectivity."""
            try:
                # This would normally test database connection
                # For now, return True as placeholder
                return {
                    "healthy": True,
                    "message": "Database connection OK",
                    "metrics": {"connection_pool_size": 10}
                }
            except Exception as e:
                return {
                    "healthy": False,
                    "message": f"Database error: {str(e)}"
                }
        
        def system_resources_health_check():
            """Check system resource usage."""
            try:
                if not PSUTIL_AVAILABLE:
                    return {
                        "healthy": True,
                        "message": "System resources check skipped (psutil not available)",
                        "metrics": {}
                    }
                
                cpu_percent = psutil.cpu_percent()
                memory = psutil.virtual_memory()
                disk = psutil.disk_usage('/')
                
                # Define thresholds
                cpu_threshold = 90.0
                memory_threshold = 90.0
                disk_threshold = 95.0
                
                issues = []
                if cpu_percent > cpu_threshold:
                    issues.append(f"High CPU usage: {cpu_percent:.1f}%")
                if memory.percent > memory_threshold:
                    issues.append(f"High memory usage: {memory.percent:.1f}%")
                if (disk.used / disk.total * 100) > disk_threshold:
                    issues.append(f"High disk usage: {disk.used / disk.total * 100:.1f}%")
                
                return {
                    "healthy": len(issues) == 0,
                    "message": "System resources OK" if not issues else "; ".join(issues),
                    "metrics": {
                        "cpu_percent": cpu_percent,
                        "memory_percent": memory.percent,
                        "disk_percent": disk.used / disk.total * 100
                    }
                }
            except Exception as e:
                return {
                    "healthy": False,
                    "message": f"System check error: {str(e)}"
                }
        
        # Register health checks
        self.health_checker.register_health_check("database", database_health_check)
        self.health_checker.register_health_check("system_resources", system_resources_health_check)
    
    def get_monitoring_dashboard(self) -> Dict[str, Any]:
        """Get comprehensive monitoring dashboard data."""
        return {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "monitoring_active": self.monitoring_active,
            "metrics": {
                "latest_values": self.metrics_collector.get_latest_values(),
                "total_metrics": len(self.metrics_collector.metrics)
            },
            "health": {
                component: status.to_dict()
                for component, status in self.health_checker.health_status.items()
            },
            "overall_healthy": self.health_checker.get_overall_health()
        }
    
    def export_metrics(self, format: str = "json") -> str:
        """Export metrics in specified format."""
        if format.lower() == "json":
            return json.dumps(self.metrics_collector.get_all_metrics(), indent=2)
        else:
            raise ValueError(f"Unsupported export format: {format}")


# Global monitoring instance
monitoring_system = MonitoringSystem()


# Convenience functions for easy access
def record_metric(name: str, value: float, tags: Dict[str, str] = None):
    """Record a metric point."""
    monitoring_system.metrics_collector.record_metric(name, value, tags)


def record_request(endpoint: str, method: str = "GET"):
    """Record an API request."""
    monitoring_system.app_monitor.record_request(endpoint, method)


def record_error(endpoint: str, error_type: str, method: str = "GET"):
    """Record an application error."""
    monitoring_system.app_monitor.record_error(endpoint, error_type, method)


def time_operation(operation_name: str, tags: Dict[str, str] = None):
    """Context manager to time operations."""
    return monitoring_system.app_monitor.time_operation(operation_name, tags)


async def get_system_health() -> Dict[str, Any]:
    """Get current system health status."""
    await monitoring_system.health_checker.check_all_health()
    return monitoring_system.get_monitoring_dashboard()


def get_logger(name: str = None) -> logging.Logger:
    """Get a logger instance."""
    if name:
        return logging.getLogger(f"mcp_data_scientist.{name}")
    return monitoring_system.logger