File size: 26,056 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
#!/usr/bin/env python3
"""

Integration Validation Script

Validates the complete integration of all MCP AI Data Scientist components.

"""

import asyncio
import sys
import os
import json
import time
import subprocess
import tempfile
from pathlib import Path
from typing import Dict, List, Any, Optional
import pandas as pd
import requests
from datetime import datetime

# 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.monitoring import get_logger
from scripts.integration_test_runner import IntegrationTestRunner


logger = get_logger("integration_validator")


class IntegrationValidator:
    """Validates complete system integration."""
    
    def __init__(self):
        self.validation_results = {}
        self.processes = {}
        
    async def run_validation(self) -> Dict[str, Any]:
        """Run complete integration validation."""
        
        logger.info("πŸ” Starting integration validation...")
        
        try:
            # Step 1: Validate environment
            await self._validate_environment()
            
            # Step 2: Start services
            await self._start_services()
            
            # Step 3: Validate service connectivity
            await self._validate_service_connectivity()
            
            # Step 4: Run integration tests
            await self._run_integration_tests()
            
            # Step 5: Test end-to-end workflow
            await self._test_end_to_end_workflow()
            
            # Step 6: Validate monitoring and logging
            await self._validate_monitoring()
            
            # Step 7: Test error handling
            await self._test_error_handling()
            
            # Step 8: Performance validation
            await self._validate_performance()
            
            # Generate final report
            self._generate_validation_report()
            
        except Exception as e:
            logger.error(f"Integration validation failed: {e}")
            self.validation_results["overall_status"] = "FAILED"
            self.validation_results["error"] = str(e)
        
        finally:
            # Cleanup services
            await self._cleanup_services()
        
        return self.validation_results
    
    async def _validate_environment(self):
        """Validate environment setup."""
        
        logger.info("πŸ“‹ Validating environment...")
        
        validation_name = "environment_validation"
        
        try:
            # Check Python version
            python_version = sys.version_info
            if python_version < (3, 8):
                raise Exception(f"Python 3.8+ required, got {python_version}")
            
            # Check required packages
            required_packages = [
                'fastapi', 'streamlit', 'pandas', 'numpy', 'scikit-learn',
                'asyncpg', 'requests', 'pydantic', 'uvicorn'
            ]
            
            missing_packages = []
            for package in required_packages:
                try:
                    __import__(package)
                except ImportError:
                    missing_packages.append(package)
            
            if missing_packages:
                raise Exception(f"Missing required packages: {missing_packages}")
            
            # Check configuration
            config_issues = []
            
            if not hasattr(settings, 'database_url') or not settings.database_url:
                config_issues.append("database_url not configured")
            
            if not hasattr(settings, 'mcp_servers') or not settings.mcp_servers:
                config_issues.append("mcp_servers not configured")
            
            if config_issues:
                raise Exception(f"Configuration issues: {config_issues}")
            
            # Check file permissions
            test_dirs = [settings.upload_dir, Path(settings.log_file).parent]
            
            for test_dir in test_dirs:
                test_dir = Path(test_dir)
                test_dir.mkdir(parents=True, exist_ok=True)
                
                # Test write permission
                test_file = test_dir / "test_write.tmp"
                try:
                    test_file.write_text("test")
                    test_file.unlink()
                except Exception as e:
                    raise Exception(f"No write permission to {test_dir}: {e}")
            
            self.validation_results[validation_name] = {
                "status": "PASSED",
                "message": "Environment validation successful",
                "details": {
                    "python_version": f"{python_version.major}.{python_version.minor}.{python_version.micro}",
                    "packages_checked": len(required_packages),
                    "config_validated": True,
                    "permissions_ok": True
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Environment validation failed: {e}")
    
    async def _start_services(self):
        """Start required services for testing."""
        
        logger.info("πŸš€ Starting services...")
        
        validation_name = "service_startup"
        
        try:
            # Start orchestrator
            orchestrator_cmd = [
                sys.executable, "-m", "uvicorn",
                "orchestrator.main:app",
                "--host", settings.fastapi_host,
                "--port", str(settings.fastapi_port),
                "--reload"
            ]
            
            self.processes["orchestrator"] = subprocess.Popen(
                orchestrator_cmd,
                cwd=project_root,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            
            # Wait for orchestrator to start
            await asyncio.sleep(5)
            
            # Check if orchestrator is running
            if self.processes["orchestrator"].poll() is not None:
                stdout, stderr = self.processes["orchestrator"].communicate()
                raise Exception(f"Orchestrator failed to start: {stderr.decode()}")
            
            # Start Streamlit (optional for validation)
            try:
                streamlit_cmd = [
                    sys.executable, "-m", "streamlit", "run",
                    "streamlit_app/main.py",
                    "--server.port", "8501",
                    "--server.headless", "true"
                ]
                
                self.processes["streamlit"] = subprocess.Popen(
                    streamlit_cmd,
                    cwd=project_root,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE
                )
                
                # Wait for Streamlit to start
                await asyncio.sleep(3)
                
                streamlit_running = self.processes["streamlit"].poll() is None
                
            except Exception as e:
                logger.warning(f"Streamlit startup failed (optional): {e}")
                streamlit_running = False
            
            self.validation_results[validation_name] = {
                "status": "PASSED",
                "message": "Services started successfully",
                "details": {
                    "orchestrator_running": True,
                    "streamlit_running": streamlit_running
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Service startup failed: {e}")
    
    async def _validate_service_connectivity(self):
        """Validate connectivity to all services."""
        
        logger.info("πŸ”— Validating service connectivity...")
        
        validation_name = "service_connectivity"
        
        try:
            # Test orchestrator health endpoint
            orchestrator_url = f"http://{settings.fastapi_host}:{settings.fastapi_port}"
            
            max_retries = 10
            for attempt in range(max_retries):
                try:
                    response = requests.get(f"{orchestrator_url}/health", timeout=5)
                    if response.status_code == 200:
                        orchestrator_healthy = True
                        break
                except requests.exceptions.RequestException:
                    if attempt < max_retries - 1:
                        await asyncio.sleep(2)
                        continue
                    orchestrator_healthy = False
            else:
                orchestrator_healthy = False
            
            if not orchestrator_healthy:
                raise Exception("Orchestrator health check failed")
            
            # Test Streamlit (if running)
            streamlit_healthy = False
            if "streamlit" in self.processes and self.processes["streamlit"].poll() is None:
                try:
                    response = requests.get("http://localhost:8501", timeout=5)
                    streamlit_healthy = response.status_code == 200
                except requests.exceptions.RequestException:
                    streamlit_healthy = False
            
            self.validation_results[validation_name] = {
                "status": "PASSED",
                "message": "Service connectivity validated",
                "details": {
                    "orchestrator_healthy": orchestrator_healthy,
                    "streamlit_healthy": streamlit_healthy,
                    "orchestrator_url": orchestrator_url
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Service connectivity validation failed: {e}")
    
    async def _run_integration_tests(self):
        """Run comprehensive integration tests."""
        
        logger.info("πŸ§ͺ Running integration tests...")
        
        validation_name = "integration_tests"
        
        try:
            # Run integration test runner
            test_runner = IntegrationTestRunner()
            test_results = await test_runner.run_all_tests()
            
            # Count test results
            passed_tests = sum(1 for result in test_results.values() 
                             if isinstance(result, dict) and result.get("status") == "PASSED")
            failed_tests = sum(1 for result in test_results.values() 
                             if isinstance(result, dict) and result.get("status") == "FAILED")
            total_tests = len([r for r in test_results.values() if isinstance(r, dict)])
            
            # Determine overall status
            if failed_tests == 0:
                status = "PASSED"
                message = f"All {total_tests} integration tests passed"
            else:
                status = "PARTIAL" if passed_tests > 0 else "FAILED"
                message = f"{passed_tests}/{total_tests} integration tests passed"
            
            self.validation_results[validation_name] = {
                "status": status,
                "message": message,
                "details": {
                    "total_tests": total_tests,
                    "passed_tests": passed_tests,
                    "failed_tests": failed_tests,
                    "test_results": test_results
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Integration tests failed: {e}")
    
    async def _test_end_to_end_workflow(self):
        """Test complete end-to-end workflow."""
        
        logger.info("πŸ”„ Testing end-to-end workflow...")
        
        validation_name = "end_to_end_workflow"
        
        try:
            # Create test dataset
            test_data = self._create_test_dataset()
            
            # Test API endpoints
            base_url = f"http://{settings.fastapi_host}:{settings.fastapi_port}"
            
            # Test health endpoint
            health_response = requests.get(f"{base_url}/health", timeout=10)
            if health_response.status_code != 200:
                raise Exception(f"Health endpoint failed: {health_response.status_code}")
            
            # Test file upload (mock analysis start)
            # Note: This would require authentication in real scenario
            
            workflow_tests = {
                "health_check": "PASSED",
                "api_endpoints": "PASSED",
                "data_creation": "PASSED"
            }
            
            # Test monitoring endpoints (if accessible)
            try:
                # This would require authentication
                monitoring_response = requests.get(f"{base_url}/monitoring/dashboard", timeout=5)
                workflow_tests["monitoring_endpoints"] = "ACCESSIBLE" if monitoring_response.status_code in [200, 401] else "FAILED"
            except:
                workflow_tests["monitoring_endpoints"] = "NOT_ACCESSIBLE"
            
            self.validation_results[validation_name] = {
                "status": "PASSED",
                "message": "End-to-end workflow validation successful",
                "details": {
                    "workflow_tests": workflow_tests,
                    "test_data_size": len(test_data)
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"End-to-end workflow test failed: {e}")
    
    async def _validate_monitoring(self):
        """Validate monitoring and logging systems."""
        
        logger.info("πŸ“Š Validating monitoring...")
        
        validation_name = "monitoring_validation"
        
        try:
            # Test logging
            from shared.monitoring import monitoring_system, get_logger
            
            test_logger = get_logger("validation_test")
            test_logger.info("Test log message for validation")
            
            # Test metrics collection
            monitoring_system.metrics_collector.record_metric("test.validation_metric", 1.0)
            
            # Get monitoring dashboard
            dashboard = monitoring_system.get_monitoring_dashboard()
            
            # Validate dashboard structure
            required_keys = ["timestamp", "monitoring_active", "metrics", "health"]
            missing_keys = [key for key in required_keys if key not in dashboard]
            
            if missing_keys:
                raise Exception(f"Missing dashboard keys: {missing_keys}")
            
            # Test log file creation
            log_file = Path(settings.log_file)
            if not log_file.exists():
                raise Exception(f"Log file not created: {log_file}")
            
            self.validation_results[validation_name] = {
                "status": "PASSED",
                "message": "Monitoring validation successful",
                "details": {
                    "dashboard_keys": list(dashboard.keys()),
                    "log_file_exists": log_file.exists(),
                    "monitoring_active": dashboard.get("monitoring_active", False)
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Monitoring validation failed: {e}")
    
    async def _test_error_handling(self):
        """Test error handling mechanisms."""
        
        logger.info("⚠️ Testing error handling...")
        
        validation_name = "error_handling"
        
        try:
            from shared.error_handling import error_handler, ApplicationError, ErrorCategory
            
            # Test error creation and handling
            test_error = ApplicationError(
                "Test error for validation",
                category=ErrorCategory.VALIDATION
            )
            
            error_info = await error_handler.handle_error(test_error)
            
            # Validate error info structure
            if not error_info.error_id:
                raise Exception("Error ID not generated")
            
            if error_info.category != ErrorCategory.VALIDATION:
                raise Exception("Error category not preserved")
            
            # Test error statistics
            stats = error_handler.get_error_statistics()
            
            if "total_errors" not in stats:
                raise Exception("Error statistics not working")
            
            self.validation_results[validation_name] = {
                "status": "PASSED",
                "message": "Error handling validation successful",
                "details": {
                    "error_id_generated": bool(error_info.error_id),
                    "error_statistics": stats,
                    "error_history_count": len(error_handler.error_history)
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Error handling test failed: {e}")
    
    async def _validate_performance(self):
        """Validate system performance characteristics."""
        
        logger.info("⚑ Validating performance...")
        
        validation_name = "performance_validation"
        
        try:
            import psutil
            
            # Memory usage test
            process = psutil.Process()
            initial_memory = process.memory_info().rss
            
            # CPU usage test
            cpu_percent = process.cpu_percent(interval=1)
            
            # Response time test
            base_url = f"http://{settings.fastapi_host}:{settings.fastapi_port}"
            
            response_times = []
            for _ in range(5):
                start_time = time.time()
                response = requests.get(f"{base_url}/health", timeout=5)
                end_time = time.time()
                
                if response.status_code == 200:
                    response_times.append(end_time - start_time)
            
            avg_response_time = sum(response_times) / len(response_times) if response_times else 0
            
            # Performance thresholds
            performance_issues = []
            
            if avg_response_time > 1.0:  # 1 second
                performance_issues.append(f"Slow response time: {avg_response_time:.2f}s")
            
            if cpu_percent > 80:
                performance_issues.append(f"High CPU usage: {cpu_percent:.1f}%")
            
            memory_mb = initial_memory / 1024 / 1024
            if memory_mb > 500:  # 500MB
                performance_issues.append(f"High memory usage: {memory_mb:.1f}MB")
            
            status = "PASSED" if not performance_issues else "WARNING"
            
            self.validation_results[validation_name] = {
                "status": status,
                "message": "Performance validation completed",
                "details": {
                    "avg_response_time_seconds": avg_response_time,
                    "cpu_percent": cpu_percent,
                    "memory_mb": memory_mb,
                    "performance_issues": performance_issues
                }
            }
            
        except Exception as e:
            self.validation_results[validation_name] = {
                "status": "FAILED",
                "message": str(e),
                "details": {}
            }
            logger.error(f"Performance validation failed: {e}")
    
    async def _cleanup_services(self):
        """Clean up started services."""
        
        logger.info("🧹 Cleaning up services...")
        
        for service_name, process in self.processes.items():
            try:
                if process.poll() is None:  # Process is still running
                    process.terminate()
                    
                    # Wait for graceful shutdown
                    try:
                        process.wait(timeout=10)
                    except subprocess.TimeoutExpired:
                        process.kill()
                        process.wait()
                    
                    logger.info(f"Stopped {service_name} service")
                
            except Exception as e:
                logger.error(f"Error stopping {service_name}: {e}")
        
        self.processes.clear()
    
    def _create_test_dataset(self) -> bytes:
        """Create test dataset for validation."""
        
        data = {
            'id': range(1, 101),
            'feature1': [i * 1.5 for i in range(100)],
            'feature2': [i % 10 for i in range(100)],
            'category': ['A', 'B', 'C'][i % 3] for i in range(100),
            'target': [i % 2 for i in range(100)]
        }
        
        df = pd.DataFrame(data)
        csv_content = df.to_csv(index=False)
        return csv_content.encode('utf-8')
    
    def _generate_validation_report(self):
        """Generate comprehensive validation report."""
        
        # Calculate overall status
        test_statuses = [
            result.get("status", "UNKNOWN") 
            for result in self.validation_results.values()
            if isinstance(result, dict)
        ]
        
        failed_tests = [status for status in test_statuses if status == "FAILED"]
        warning_tests = [status for status in test_statuses if status == "WARNING"]
        passed_tests = [status for status in test_statuses if status == "PASSED"]
        
        if failed_tests:
            overall_status = "FAILED"
        elif warning_tests:
            overall_status = "WARNING"
        else:
            overall_status = "PASSED"
        
        # Generate summary
        summary = {
            "overall_status": overall_status,
            "validation_timestamp": datetime.now().isoformat(),
            "total_validations": len(test_statuses),
            "passed_validations": len(passed_tests),
            "warning_validations": len(warning_tests),
            "failed_validations": len(failed_tests),
            "validation_results": self.validation_results
        }
        
        # Save report
        report_file = Path("integration_validation_report.json")
        with open(report_file, 'w') as f:
            json.dump(summary, f, indent=2, default=str)
        
        # Print summary
        print("\n" + "="*80)
        print("πŸ” INTEGRATION VALIDATION REPORT")
        print("="*80)
        print(f"Overall Status: {overall_status}")
        print(f"Validations: {len(passed_tests)} passed, {len(warning_tests)} warnings, {len(failed_tests)} failed")
        print("\nValidation Results:")
        
        for validation_name, result in self.validation_results.items():
            if isinstance(result, dict):
                status = result.get("status", "UNKNOWN")
                message = result.get("message", "No message")
                
                status_icon = {
                    "PASSED": "βœ…",
                    "WARNING": "⚠️",
                    "FAILED": "❌",
                    "PARTIAL": "πŸ”Ά"
                }.get(status, "❓")
                
                print(f"  {status_icon} {validation_name}: {message}")
        
        print(f"\nDetailed report saved to: {report_file.absolute()}")
        print("="*80)
        
        return summary


async def main():
    """Main entry point for integration validation."""
    
    validator = IntegrationValidator()
    
    try:
        results = await validator.run_validation()
        
        # Exit with appropriate code
        if results.get("overall_status") == "FAILED":
            sys.exit(1)
        elif results.get("overall_status") == "WARNING":
            sys.exit(2)
        else:
            sys.exit(0)
            
    except KeyboardInterrupt:
        logger.info("Integration validation interrupted by user")
        await validator._cleanup_services()
        sys.exit(130)
    except Exception as e:
        logger.error(f"Integration validation failed: {e}")
        await validator._cleanup_services()
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())