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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
#!/usr/bin/env python3
"""

Integration validation script for MCP AI Data Scientist.

Validates that all components are properly integrated and working together.

"""

import asyncio
import sys
import os
import json
import time
from pathlib import Path
from datetime import datetime
from typing import Dict, Any, List

# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from shared.config import settings
from shared.database import test_database_connection
from shared.integration_coordinator import integration_coordinator
from shared.monitoring import monitoring_system, record_metric
from shared.error_handling import error_handler, ErrorContext


class IntegrationValidator:
    """Comprehensive integration validator."""
    
    def __init__(self):
        self.validation_results = {}
        self.start_time = datetime.now()
    
    async def run_all_validations(self) -> Dict[str, Any]:
        """Run all integration validations."""
        
        print("πŸ” MCP AI Data Scientist Integration Validation")
        print("=" * 60)
        
        validations = [
            ("Database Connection", self._validate_database),
            ("Configuration", self._validate_configuration),
            ("Component Imports", self._validate_imports),
            ("Integration Coordinator", self._validate_integration_coordinator),
            ("Monitoring System", self._validate_monitoring),
            ("Error Handling", self._validate_error_handling),
            ("MCP Server Configs", self._validate_mcp_configs),
            ("API Endpoints", self._validate_api_endpoints),
            ("Streamlit Components", self._validate_streamlit),
            ("End-to-End Pipeline", self._validate_pipeline)
        ]
        
        for name, validation_func in validations:
            print(f"\nπŸ§ͺ {name}...")
            try:
                result = await validation_func()
                if result["success"]:
                    print(f"   βœ… {result['message']}")
                else:
                    print(f"   ❌ {result['message']}")
                
                self.validation_results[name] = result
                
            except Exception as e:
                error_result = {
                    "success": False,
                    "message": f"Validation error: {str(e)}",
                    "details": {}
                }
                print(f"   ❌ {error_result['message']}")
                self.validation_results[name] = error_result
        
        # Generate summary
        return self._generate_summary()
    
    async def _validate_database(self) -> Dict[str, Any]:
        """Validate database connectivity and schema."""
        
        try:
            # Test basic connection
            db_ok = await test_database_connection()
            if not db_ok:
                return {
                    "success": False,
                    "message": "Database connection failed",
                    "details": {}
                }
            
            # Test schema validation
            from shared.database import get_database_connection
            
            async with get_database_connection() as conn:
                # Check for key tables
                tables_to_check = ['users', 'analysis_sessions', 'user_datasets']
                existing_tables = []
                
                for table in tables_to_check:
                    exists = await conn.fetchval(
                        "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = $1)",
                        table
                    )
                    if exists:
                        existing_tables.append(table)
                
                return {
                    "success": True,
                    "message": f"Database connection OK, {len(existing_tables)}/{len(tables_to_check)} tables found",
                    "details": {
                        "existing_tables": existing_tables,
                        "missing_tables": list(set(tables_to_check) - set(existing_tables))
                    }
                }
                
        except Exception as e:
            return {
                "success": False,
                "message": f"Database validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_configuration(self) -> Dict[str, Any]:
        """Validate system configuration."""
        
        try:
            required_settings = [
                'database_url', 'fastapi_host', 'fastapi_port',
                'upload_dir', 'log_level', 'mcp_servers'
            ]
            
            missing_settings = []
            for setting in required_settings:
                if not hasattr(settings, setting) or getattr(settings, setting) is None:
                    missing_settings.append(setting)
            
            if missing_settings:
                return {
                    "success": False,
                    "message": f"Missing required settings: {missing_settings}",
                    "details": {"missing_settings": missing_settings}
                }
            
            # Validate MCP server configurations
            mcp_servers = settings.mcp_servers
            if not mcp_servers:
                return {
                    "success": False,
                    "message": "No MCP servers configured",
                    "details": {}
                }
            
            return {
                "success": True,
                "message": f"Configuration valid, {len(mcp_servers)} MCP servers configured",
                "details": {
                    "mcp_servers": list(mcp_servers.keys()),
                    "upload_dir": str(settings.upload_dir),
                    "log_level": settings.log_level
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Configuration validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_imports(self) -> Dict[str, Any]:
        """Validate that all components can be imported."""
        
        try:
            import_tests = [
                ("orchestrator.main", "app"),
                ("orchestrator.analysis_orchestrator", "AnalysisOrchestrator"),
                ("orchestrator.mcp_client_manager", "MCPClientManager"),
                ("orchestrator.sse_manager", "SSEManager"),
                ("shared.monitoring", "monitoring_system"),
                ("shared.error_handling", "error_handler"),
                ("shared.integration_coordinator", "integration_coordinator"),
                ("streamlit_app.main", "main"),
                ("streamlit_app.utils.api_client", "APIClient")
            ]
            
            successful_imports = []
            failed_imports = []
            
            for module_name, class_name in import_tests:
                try:
                    module = __import__(module_name, fromlist=[class_name])
                    getattr(module, class_name)
                    successful_imports.append(f"{module_name}.{class_name}")
                except Exception as e:
                    failed_imports.append(f"{module_name}.{class_name}: {str(e)}")
            
            if failed_imports:
                return {
                    "success": False,
                    "message": f"Import failures: {len(failed_imports)}/{len(import_tests)}",
                    "details": {
                        "successful": successful_imports,
                        "failed": failed_imports
                    }
                }
            
            return {
                "success": True,
                "message": f"All imports successful: {len(successful_imports)}/{len(import_tests)}",
                "details": {"successful_imports": successful_imports}
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Import validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_integration_coordinator(self) -> Dict[str, Any]:
        """Validate integration coordinator functionality."""
        
        try:
            # Test initialization
            success = await integration_coordinator.initialize_system()
            
            if not success:
                return {
                    "success": False,
                    "message": "Integration coordinator initialization failed",
                    "details": {}
                }
            
            # Get system status
            status = integration_coordinator.get_system_status()
            
            # Shutdown
            await integration_coordinator.shutdown_system()
            
            return {
                "success": True,
                "message": "Integration coordinator working correctly",
                "details": {
                    "initialization_complete": status.get("initialization_complete", False),
                    "components_status": status.get("components_status", {})
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Integration coordinator validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_monitoring(self) -> Dict[str, Any]:
        """Validate monitoring system."""
        
        try:
            # Start monitoring
            await monitoring_system.start_monitoring()
            
            # Record test metric
            record_metric("validation.test_metric", 42.0, tags={"test": "true"})
            
            # Check metrics were recorded
            latest_values = monitoring_system.metrics_collector.get_latest_values()
            
            # Stop monitoring
            await monitoring_system.stop_monitoring()
            
            if "validation.test_metric" not in latest_values:
                return {
                    "success": False,
                    "message": "Monitoring system not recording metrics",
                    "details": {}
                }
            
            return {
                "success": True,
                "message": "Monitoring system working correctly",
                "details": {
                    "metrics_recorded": len(latest_values),
                    "test_metric_value": latest_values.get("validation.test_metric")
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Monitoring validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_error_handling(self) -> Dict[str, Any]:
        """Validate error handling system."""
        
        try:
            # Generate test error
            test_error = ValueError("Validation test error")
            
            # Handle error
            error_info = await error_handler.handle_error(
                test_error,
                ErrorContext(
                    component="validation",
                    operation="test_error_handling"
                ),
                attempt_recovery=False
            )
            
            if not error_info or not error_info.error_id:
                return {
                    "success": False,
                    "message": "Error handling system not working",
                    "details": {}
                }
            
            return {
                "success": True,
                "message": "Error handling system working correctly",
                "details": {
                    "error_id": error_info.error_id,
                    "category": error_info.category.value,
                    "severity": error_info.severity.value
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Error handling validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_mcp_configs(self) -> Dict[str, Any]:
        """Validate MCP server configurations."""
        
        try:
            required_servers = [
                'data_cleaning', 'hypothesis_testing', 'preprocessing',
                'feature_engineering', 'model_training', 'action_generation'
            ]
            
            configured_servers = list(settings.mcp_servers.keys())
            missing_servers = set(required_servers) - set(configured_servers)
            
            if missing_servers:
                return {
                    "success": False,
                    "message": f"Missing MCP servers: {missing_servers}",
                    "details": {
                        "configured": configured_servers,
                        "missing": list(missing_servers)
                    }
                }
            
            # Validate server configurations
            config_issues = []
            for server_name, config in settings.mcp_servers.items():
                required_keys = ['host', 'port']
                missing_keys = [key for key in required_keys if key not in config]
                
                if missing_keys:
                    config_issues.append(f"{server_name}: missing {missing_keys}")
            
            if config_issues:
                return {
                    "success": False,
                    "message": f"MCP configuration issues: {config_issues}",
                    "details": {"issues": config_issues}
                }
            
            return {
                "success": True,
                "message": f"All {len(configured_servers)} MCP servers properly configured",
                "details": {"configured_servers": configured_servers}
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"MCP config validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_api_endpoints(self) -> Dict[str, Any]:
        """Validate API endpoint structure."""
        
        try:
            from orchestrator.main import app
            
            # Get all routes
            routes = []
            for route in app.routes:
                if hasattr(route, 'path') and hasattr(route, 'methods'):
                    routes.append({
                        "path": route.path,
                        "methods": list(route.methods) if route.methods else []
                    })
            
            # Check for required endpoints
            required_endpoints = [
                "/health",
                "/analysis/start",
                "/analysis/{session_id}/status",
                "/analysis/{session_id}/results",
                "/events/stream"
            ]
            
            existing_paths = [route["path"] for route in routes]
            missing_endpoints = [
                endpoint for endpoint in required_endpoints
                if endpoint not in existing_paths
            ]
            
            if missing_endpoints:
                return {
                    "success": False,
                    "message": f"Missing API endpoints: {missing_endpoints}",
                    "details": {
                        "existing_endpoints": existing_paths,
                        "missing_endpoints": missing_endpoints
                    }
                }
            
            return {
                "success": True,
                "message": f"All required API endpoints present: {len(routes)} total routes",
                "details": {"total_routes": len(routes)}
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"API endpoint validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_streamlit(self) -> Dict[str, Any]:
        """Validate Streamlit components."""
        
        try:
            # Test Streamlit component imports
            components_to_test = [
                ('streamlit_app.components.auth', 'AuthManager'),
                ('streamlit_app.components.file_upload', 'FileUploadComponent'),
                ('streamlit_app.utils.api_client', 'APIClient'),
                ('streamlit_app.utils.sse_client', 'SSEClient')
            ]
            
            successful_imports = []
            failed_imports = []
            
            for module_name, class_name in components_to_test:
                try:
                    module = __import__(module_name, fromlist=[class_name])
                    getattr(module, class_name)
                    successful_imports.append(f"{module_name}.{class_name}")
                except Exception as e:
                    failed_imports.append(f"{module_name}.{class_name}: {str(e)}")
            
            # Test main Streamlit app
            try:
                import streamlit_app.main
                main_app_ok = True
            except Exception as e:
                main_app_ok = False
                failed_imports.append(f"streamlit_app.main: {str(e)}")
            
            success_rate = len(successful_imports) / len(components_to_test)
            
            return {
                "success": success_rate >= 0.8,  # Allow some failures for optional components
                "message": f"Streamlit validation: {len(successful_imports)}/{len(components_to_test)} components OK",
                "details": {
                    "successful_imports": successful_imports,
                    "failed_imports": failed_imports,
                    "main_app_ok": main_app_ok
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Streamlit validation failed: {str(e)}",
                "details": {}
            }
    
    async def _validate_pipeline(self) -> Dict[str, Any]:
        """Validate end-to-end pipeline structure."""
        
        try:
            from orchestrator.analysis_orchestrator import AnalysisOrchestrator
            from orchestrator.mcp_client_manager import MCPClientManager
            from orchestrator.sse_manager import SSEManager
            from orchestrator.session_manager_simple import SessionManager
            
            # Test component creation
            mcp_client = MCPClientManager()
            sse_manager = SSEManager()
            session_manager = SessionManager()
            orchestrator = AnalysisOrchestrator(mcp_client, sse_manager, session_manager)
            
            # Verify pipeline stages
            if not hasattr(orchestrator, 'pipeline_stages'):
                return {
                    "success": False,
                    "message": "Pipeline stages not configured",
                    "details": {}
                }
            
            expected_stages = 6  # Number of expected pipeline stages
            actual_stages = len(orchestrator.pipeline_stages)
            
            if actual_stages != expected_stages:
                return {
                    "success": False,
                    "message": f"Pipeline stage count mismatch: expected {expected_stages}, got {actual_stages}",
                    "details": {
                        "expected_stages": expected_stages,
                        "actual_stages": actual_stages,
                        "pipeline_stages": list(orchestrator.pipeline_stages.keys())
                    }
                }
            
            return {
                "success": True,
                "message": f"Pipeline structure valid: {actual_stages} stages configured",
                "details": {
                    "pipeline_stages": list(orchestrator.pipeline_stages.keys()),
                    "stage_count": actual_stages
                }
            }
            
        except Exception as e:
            return {
                "success": False,
                "message": f"Pipeline validation failed: {str(e)}",
                "details": {}
            }
    
    def _generate_summary(self) -> Dict[str, Any]:
        """Generate validation summary."""
        
        end_time = datetime.now()
        duration = end_time - self.start_time
        
        successful_validations = [
            name for name, result in self.validation_results.items()
            if result.get("success", False)
        ]
        
        failed_validations = [
            name for name, result in self.validation_results.items()
            if not result.get("success", False)
        ]
        
        overall_success = len(failed_validations) == 0
        
        summary = {
            "overall_success": overall_success,
            "start_time": self.start_time.isoformat(),
            "end_time": end_time.isoformat(),
            "duration_seconds": duration.total_seconds(),
            "total_validations": len(self.validation_results),
            "successful_validations": len(successful_validations),
            "failed_validations": len(failed_validations),
            "validation_results": self.validation_results,
            "successful_validation_names": successful_validations,
            "failed_validation_names": failed_validations
        }
        
        # Print summary
        print("\n" + "=" * 60)
        print("πŸ“Š VALIDATION SUMMARY")
        print("=" * 60)
        print(f"Overall Status: {'βœ… PASSED' if overall_success else '❌ FAILED'}")
        print(f"Duration: {duration.total_seconds():.2f} seconds")
        print(f"Validations: {len(successful_validations)}/{len(self.validation_results)} passed")
        
        if failed_validations:
            print(f"\n❌ Failed Validations:")
            for name in failed_validations:
                print(f"  β€’ {name}")
        
        print("=" * 60)
        
        return summary


async def main():
    """Main validation function."""
    
    validator = IntegrationValidator()
    
    try:
        summary = await validator.run_all_validations()
        
        # Save detailed report
        report_file = Path("integration_validation_report.json")
        with open(report_file, 'w') as f:
            json.dump(summary, f, indent=2, default=str)
        
        print(f"\nπŸ“„ Detailed report saved to: {report_file}")
        
        # Exit with appropriate code
        return summary["overall_success"]
        
    except Exception as e:
        print(f"\n❌ Validation failed with error: {e}")
        return False


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)