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

Deployment Validation Script



Validates the complete deployment of the MCP AI Data Scientist system.

Checks configuration, connectivity, and functionality of all components.

"""

import asyncio
import aiohttp
import json
import os
import sys
import time
import subprocess
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass
import logging


@dataclass
class ValidationResult:
    """Result of a validation check."""
    check_name: str
    passed: bool
    message: str
    details: Optional[Dict] = None


class DeploymentValidator:
    """Validates MCP AI Data Scientist deployment."""
    
    def __init__(self):
        self.logger = self._setup_logging()
        self.results: List[ValidationResult] = []
    
    def _setup_logging(self) -> logging.Logger:
        """Setup logging configuration."""
        logger = logging.getLogger("deployment_validator")
        logger.setLevel(logging.INFO)
        
        if not logger.handlers:
            handler = logging.StreamHandler()
            formatter = logging.Formatter(
                '%(asctime)s - %(levelname)s - %(message)s'
            )
            handler.setFormatter(formatter)
            logger.addHandler(handler)
        
        return logger
    
    def add_result(self, check_name: str, passed: bool, message: str, details: Optional[Dict] = None):
        """Add validation result."""
        result = ValidationResult(check_name, passed, message, details)
        self.results.append(result)
        
        status = "✅ PASS" if passed else "❌ FAIL"
        self.logger.info(f"{status} - {check_name}: {message}")
    
    def validate_prerequisites(self) -> bool:
        """Validate deployment prerequisites."""
        self.logger.info("Validating prerequisites...")
        
        # Check Docker
        try:
            result = subprocess.run(["docker", "--version"], capture_output=True, text=True)
            if result.returncode == 0:
                self.add_result("Docker Installation", True, f"Docker found: {result.stdout.strip()}")
            else:
                self.add_result("Docker Installation", False, "Docker not found or not working")
                return False
        except FileNotFoundError:
            self.add_result("Docker Installation", False, "Docker command not found")
            return False
        
        # Check Docker Compose
        try:
            result = subprocess.run(["docker-compose", "--version"], capture_output=True, text=True)
            if result.returncode == 0:
                self.add_result("Docker Compose Installation", True, f"Docker Compose found: {result.stdout.strip()}")
            else:
                self.add_result("Docker Compose Installation", False, "Docker Compose not found or not working")
                return False
        except FileNotFoundError:
            self.add_result("Docker Compose Installation", False, "Docker Compose command not found")
            return False
        
        return True
    
    def validate_configuration_files(self) -> bool:
        """Validate configuration files exist and are valid."""
        self.logger.info("Validating configuration files...")
        
        required_files = [
            "docker-compose.yml",
            ".env",
            "requirements.txt"
        ]
        
        all_valid = True
        
        for file in required_files:
            if os.path.exists(file):
                self.add_result(f"Configuration File: {file}", True, f"File exists")
            else:
                self.add_result(f"Configuration File: {file}", False, f"File missing")
                all_valid = False
        
        # Validate docker-compose.yml syntax
        try:
            result = subprocess.run(
                ["docker-compose", "config"],
                capture_output=True,
                text=True
            )
            if result.returncode == 0:
                self.add_result("Docker Compose Syntax", True, "Configuration is valid")
            else:
                self.add_result("Docker Compose Syntax", False, f"Syntax error: {result.stderr}")
                all_valid = False
        except Exception as e:
            self.add_result("Docker Compose Syntax", False, f"Validation failed: {str(e)}")
            all_valid = False
        
        return all_valid
    
    def validate_environment_variables(self) -> bool:
        """Validate required environment variables."""
        self.logger.info("Validating environment variables...")
        
        required_vars = [
            "SUPABASE_URL",
            "SUPABASE_ANON_KEY", 
            "SUPABASE_SERVICE_ROLE_KEY",
            "CLERK_SECRET_KEY",
            "CLERK_PUBLISHABLE_KEY",
            "GEMINI_API_KEY"
        ]
        
        all_valid = True
        
        # Load .env file
        env_vars = {}
        if os.path.exists(".env"):
            with open(".env", "r") as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith("#") and "=" in line:
                        key, value = line.split("=", 1)
                        env_vars[key] = value
        
        for var in required_vars:
            if var in env_vars and env_vars[var] and env_vars[var] != f"your-{var.lower().replace('_', '-')}-here":
                self.add_result(f"Environment Variable: {var}", True, "Variable is set")
            else:
                self.add_result(f"Environment Variable: {var}", False, "Variable missing or not configured")
                all_valid = False
        
        return all_valid
    
    def validate_docker_images(self) -> bool:
        """Validate Docker images can be built."""
        self.logger.info("Validating Docker images...")
        
        try:
            # Build images
            result = subprocess.run(
                ["docker-compose", "build"],
                capture_output=True,
                text=True,
                timeout=300  # 5 minute timeout
            )
            
            if result.returncode == 0:
                self.add_result("Docker Image Build", True, "All images built successfully")
                return True
            else:
                self.add_result("Docker Image Build", False, f"Build failed: {result.stderr}")
                return False
        
        except subprocess.TimeoutExpired:
            self.add_result("Docker Image Build", False, "Build timed out after 5 minutes")
            return False
        except Exception as e:
            self.add_result("Docker Image Build", False, f"Build error: {str(e)}")
            return False
    
    async def validate_service_startup(self) -> bool:
        """Validate services start up correctly."""
        self.logger.info("Validating service startup...")
        
        try:
            # Start services
            result = subprocess.run(
                ["docker-compose", "up", "-d"],
                capture_output=True,
                text=True
            )
            
            if result.returncode != 0:
                self.add_result("Service Startup", False, f"Failed to start services: {result.stderr}")
                return False
            
            # Wait for services to start
            self.logger.info("Waiting for services to start...")
            await asyncio.sleep(30)
            
            # Check if containers are running
            result = subprocess.run(
                ["docker-compose", "ps", "--format", "json"],
                capture_output=True,
                text=True
            )
            
            if result.returncode == 0:
                running_services = []
                for line in result.stdout.strip().split('\n'):
                    if line:
                        try:
                            container = json.loads(line)
                            if container['State'] == 'running':
                                running_services.append(container['Service'])
                        except json.JSONDecodeError:
                            continue
                
                if len(running_services) >= 6:  # At least 6 services should be running
                    self.add_result("Service Startup", True, f"{len(running_services)} services running")
                    return True
                else:
                    self.add_result("Service Startup", False, f"Only {len(running_services)} services running")
                    return False
            else:
                self.add_result("Service Startup", False, "Failed to check service status")
                return False
        
        except Exception as e:
            self.add_result("Service Startup", False, f"Startup validation error: {str(e)}")
            return False
    
    async def validate_service_health(self) -> bool:
        """Validate service health endpoints."""
        self.logger.info("Validating service health...")
        
        health_checks = [
            ("Orchestrator Health", "http://localhost:8000/health"),
            ("Streamlit Health", "http://localhost:8501/_stcore/health")
        ]
        
        all_healthy = True
        
        for check_name, url in health_checks:
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(url, timeout=10) as response:
                        if response.status == 200:
                            self.add_result(check_name, True, f"Service healthy (status: {response.status})")
                        else:
                            self.add_result(check_name, False, f"Unhealthy status: {response.status}")
                            all_healthy = False
            
            except asyncio.TimeoutError:
                self.add_result(check_name, False, "Health check timed out")
                all_healthy = False
            except Exception as e:
                self.add_result(check_name, False, f"Health check failed: {str(e)}")
                all_healthy = False
        
        return all_healthy
    
    async def validate_mcp_connectivity(self) -> bool:
        """Validate MCP server connectivity."""
        self.logger.info("Validating MCP server connectivity...")
        
        mcp_servers = [
            ("Data Cleaning MCP", 3001),
            ("Hypothesis Testing MCP", 3002),
            ("Preprocessing MCP", 3003),
            ("Feature Engineering MCP", 3004),
            ("Model Training MCP", 3005),
            ("Action Generation MCP", 3006)
        ]
        
        all_connected = True
        
        for server_name, port in mcp_servers:
            try:
                import socket
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(5)
                result = sock.connect_ex(("localhost", port))
                sock.close()
                
                if result == 0:
                    self.add_result(f"{server_name} Connectivity", True, f"Port {port} accessible")
                else:
                    self.add_result(f"{server_name} Connectivity", False, f"Port {port} not accessible")
                    all_connected = False
            
            except Exception as e:
                self.add_result(f"{server_name} Connectivity", False, f"Connection test failed: {str(e)}")
                all_connected = False
        
        return all_connected
    
    async def validate_api_endpoints(self) -> bool:
        """Validate key API endpoints."""
        self.logger.info("Validating API endpoints...")
        
        endpoints = [
            ("API Documentation", "http://localhost:8000/docs"),
            ("API OpenAPI Spec", "http://localhost:8000/openapi.json"),
            ("Health Endpoint", "http://localhost:8000/health")
        ]
        
        all_valid = True
        
        for endpoint_name, url in endpoints:
            try:
                async with aiohttp.ClientSession() as session:
                    async with session.get(url, timeout=10) as response:
                        if response.status == 200:
                            self.add_result(f"API Endpoint: {endpoint_name}", True, f"Endpoint accessible (status: {response.status})")
                        else:
                            self.add_result(f"API Endpoint: {endpoint_name}", False, f"Endpoint returned status: {response.status}")
                            all_valid = False
            
            except Exception as e:
                self.add_result(f"API Endpoint: {endpoint_name}", False, f"Endpoint test failed: {str(e)}")
                all_valid = False
        
        return all_valid
    
    def validate_security_configuration(self) -> bool:
        """Validate security configuration."""
        self.logger.info("Validating security configuration...")
        
        # Check for security-related environment variables
        security_vars = ["CLERK_SECRET_KEY", "SUPABASE_SERVICE_ROLE_KEY"]
        
        all_secure = True
        
        # Load .env file
        env_vars = {}
        if os.path.exists(".env"):
            with open(".env", "r") as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith("#") and "=" in line:
                        key, value = line.split("=", 1)
                        env_vars[key] = value
        
        for var in security_vars:
            if var in env_vars and env_vars[var]:
                # Check if it's not a placeholder
                if "your-" not in env_vars[var].lower() and "placeholder" not in env_vars[var].lower():
                    self.add_result(f"Security Config: {var}", True, "Security variable configured")
                else:
                    self.add_result(f"Security Config: {var}", False, "Security variable appears to be placeholder")
                    all_secure = False
            else:
                self.add_result(f"Security Config: {var}", False, "Security variable not configured")
                all_secure = False
        
        # Check for debug mode in production
        debug_enabled = env_vars.get("FASTAPI_DEBUG", "false").lower() == "true"
        if debug_enabled:
            self.add_result("Security Config: Debug Mode", False, "Debug mode is enabled (security risk)")
            all_secure = False
        else:
            self.add_result("Security Config: Debug Mode", True, "Debug mode is disabled")
        
        return all_secure
    
    def cleanup_test_deployment(self):
        """Clean up test deployment."""
        self.logger.info("Cleaning up test deployment...")
        
        try:
            subprocess.run(["docker-compose", "down"], capture_output=True)
            self.logger.info("Test deployment cleaned up")
        except Exception as e:
            self.logger.warning(f"Cleanup failed: {str(e)}")
    
    def generate_report(self) -> Dict:
        """Generate validation report."""
        passed_count = sum(1 for r in self.results if r.passed)
        total_count = len(self.results)
        
        report = {
            "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
            "overall_status": "PASS" if passed_count == total_count else "FAIL",
            "summary": {
                "total_checks": total_count,
                "passed": passed_count,
                "failed": total_count - passed_count,
                "success_rate": f"{(passed_count / total_count * 100):.1f}%" if total_count > 0 else "0%"
            },
            "results": [
                {
                    "check": r.check_name,
                    "status": "PASS" if r.passed else "FAIL",
                    "message": r.message,
                    "details": r.details
                }
                for r in self.results
            ]
        }
        
        return report
    
    def print_report(self):
        """Print validation report."""
        report = self.generate_report()
        
        print("\n" + "="*80)
        print("DEPLOYMENT VALIDATION REPORT")
        print("="*80)
        print(f"Timestamp: {report['timestamp']}")
        print(f"Overall Status: {report['overall_status']}")
        print(f"Success Rate: {report['summary']['success_rate']}")
        print(f"Checks: {report['summary']['passed']}/{report['summary']['total_checks']} passed")
        print()
        
        # Group results by category
        categories = {}
        for result in self.results:
            category = result.check_name.split(":")[0] if ":" in result.check_name else "General"
            if category not in categories:
                categories[category] = []
            categories[category].append(result)
        
        for category, results in categories.items():
            print(f"{category.upper()}:")
            print("-" * 40)
            
            for result in results:
                status_icon = "✅" if result.passed else "❌"
                print(f"  {status_icon} {result.check_name}: {result.message}")
            
            print()
        
        if report['overall_status'] == "FAIL":
            print("RECOMMENDATIONS:")
            print("-" * 40)
            
            failed_results = [r for r in self.results if not r.passed]
            for result in failed_results:
                print(f"• Fix {result.check_name}: {result.message}")
            
            print()
    
    async def run_full_validation(self, cleanup: bool = True) -> bool:
        """Run complete deployment validation."""
        self.logger.info("Starting deployment validation...")
        
        try:
            # Step 1: Prerequisites
            if not self.validate_prerequisites():
                return False
            
            # Step 2: Configuration
            if not self.validate_configuration_files():
                return False
            
            # Step 3: Environment variables
            if not self.validate_environment_variables():
                return False
            
            # Step 4: Security configuration
            self.validate_security_configuration()
            
            # Step 5: Docker images
            if not self.validate_docker_images():
                return False
            
            # Step 6: Service startup
            if not await self.validate_service_startup():
                return False
            
            # Step 7: Service health
            await self.validate_service_health()
            
            # Step 8: MCP connectivity
            await self.validate_mcp_connectivity()
            
            # Step 9: API endpoints
            await self.validate_api_endpoints()
            
            return True
        
        finally:
            if cleanup:
                self.cleanup_test_deployment()


async def main():
    """Main function."""
    import argparse
    
    parser = argparse.ArgumentParser(description="Validate MCP AI Data Scientist deployment")
    parser.add_argument("--no-cleanup", action="store_true", help="Don't clean up test deployment")
    parser.add_argument("--output", "-o", help="Output report to JSON file")
    
    args = parser.parse_args()
    
    validator = DeploymentValidator()
    
    try:
        success = await validator.run_full_validation(cleanup=not args.no_cleanup)
        
        # Print report
        validator.print_report()
        
        # Save report if requested
        if args.output:
            report = validator.generate_report()
            with open(args.output, 'w') as f:
                json.dump(report, f, indent=2)
            print(f"Report saved to {args.output}")
        
        # Exit with appropriate code
        sys.exit(0 if success else 1)
    
    except KeyboardInterrupt:
        validator.logger.info("Validation interrupted by user")
        validator.cleanup_test_deployment()
        sys.exit(1)
    except Exception as e:
        validator.logger.error(f"Validation failed with error: {str(e)}")
        validator.cleanup_test_deployment()
        sys.exit(1)


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