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

Integration Coordinator for MCP AI Data Scientist

Manages the integration between all system components and provides centralized coordination.

"""

import asyncio
import logging
from typing import Dict, Any, Optional, List
from datetime import datetime, timezone
from contextlib import asynccontextmanager

from .config import settings
from .monitoring import monitoring_system, get_logger, record_metric, time_operation
from .error_handling import error_handler, ErrorContext, ApplicationError, ErrorCategory
from .database import get_database_connection, test_database_connection


class IntegrationCoordinator:
    """Coordinates integration between all system components."""
    
    def __init__(self):
        self.logger = get_logger("integration_coordinator")
        self.components_status = {}
        self.initialization_complete = False
        
    async def initialize_system(self) -> bool:
        """Initialize all system components in the correct order."""
        
        self.logger.info("πŸš€ Starting system initialization...")
        
        try:
            # Step 1: Initialize monitoring system
            await self._initialize_monitoring()
            
            # Step 2: Test database connectivity
            await self._initialize_database()
            
            # Step 3: Initialize error handling
            await self._initialize_error_handling()
            
            # Step 4: Verify MCP server configurations
            await self._verify_mcp_configurations()
            
            # Step 5: Initialize orchestrator components
            await self._initialize_orchestrator_components()
            
            # Step 6: Initialize Streamlit components
            await self._verify_streamlit_components()
            
            # Step 7: Run integration tests
            await self._run_integration_tests()
            
            self.initialization_complete = True
            self.logger.info("βœ… System initialization completed successfully")
            
            # Record successful initialization
            record_metric("system.initialization_success", 1)
            
            return True
            
        except Exception as e:
            self.logger.error(f"❌ System initialization failed: {e}")
            
            # Record failed initialization
            record_metric("system.initialization_failure", 1)
            
            # Handle initialization error
            await error_handler.handle_error(
                e,
                ErrorContext(
                    component="integration_coordinator",
                    operation="initialize_system"
                )
            )
            
            return False
    
    async def _initialize_monitoring(self):
        """Initialize monitoring system."""
        
        self.logger.info("πŸ“Š Initializing monitoring system...")
        
        try:
            await monitoring_system.start_monitoring()
            self.components_status["monitoring"] = "initialized"
            self.logger.info("βœ… Monitoring system initialized")
            
        except Exception as e:
            self.components_status["monitoring"] = f"failed: {str(e)}"
            raise ApplicationError(
                f"Failed to initialize monitoring system: {e}",
                category=ErrorCategory.SYSTEM
            )
    
    async def _initialize_database(self):
        """Initialize and test database connectivity."""
        
        self.logger.info("πŸ—„οΈ Testing database connectivity...")
        
        try:
            # Test database connection
            connection_ok = await test_database_connection()
            
            if not connection_ok:
                raise ApplicationError(
                    "Database connection test failed",
                    category=ErrorCategory.DATABASE
                )
            
            # Verify required tables exist
            await self._verify_database_schema()
            
            self.components_status["database"] = "initialized"
            self.logger.info("βœ… Database connectivity verified")
            
        except Exception as e:
            self.components_status["database"] = f"failed: {str(e)}"
            raise ApplicationError(
                f"Database initialization failed: {e}",
                category=ErrorCategory.DATABASE
            )
    
    async def _verify_database_schema(self):
        """Verify that all required database tables exist."""
        
        required_tables = [
            'users', 'analysis_sessions', 'user_datasets',
            'hypotheses', 'trained_models', 'preprocessing_operations',
            'feature_engineering_results', 'business_recommendations'
        ]
        
        async with get_database_connection() as conn:
            existing_tables = []
            
            for table in required_tables:
                exists = await conn.fetchval(
                    "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_name = $1)",
                    table
                )
                if exists:
                    existing_tables.append(table)
            
            missing_tables = set(required_tables) - set(existing_tables)
            
            if missing_tables:
                self.logger.warning(f"Missing database tables: {missing_tables}")
                # Don't fail initialization for missing tables - they might be created later
            
            self.logger.info(f"Database schema check: {len(existing_tables)}/{len(required_tables)} tables found")
    
    async def _initialize_error_handling(self):
        """Initialize error handling system."""
        
        self.logger.info("⚠️ Initializing error handling...")
        
        try:
            # Register recovery handlers
            self._register_recovery_handlers()
            
            self.components_status["error_handling"] = "initialized"
            self.logger.info("βœ… Error handling initialized")
            
        except Exception as e:
            self.components_status["error_handling"] = f"failed: {str(e)}"
            raise ApplicationError(
                f"Error handling initialization failed: {e}",
                category=ErrorCategory.SYSTEM
            )
    
    def _register_recovery_handlers(self):
        """Register error recovery handlers."""
        
        from .error_handling import register_recovery_handler, ErrorCategory
        
        async def database_recovery_handler(error_info):
            """Recovery handler for database errors."""
            self.logger.info(f"Attempting database recovery for error {error_info.error_id}")
            # Implement database reconnection logic here
            
        async def mcp_server_recovery_handler(error_info):
            """Recovery handler for MCP server errors."""
            self.logger.info(f"Attempting MCP server recovery for error {error_info.error_id}")
            # Implement MCP server reconnection logic here
        
        # Register handlers
        register_recovery_handler(ErrorCategory.DATABASE, database_recovery_handler)
        register_recovery_handler(ErrorCategory.MCP_SERVER, mcp_server_recovery_handler)
    
    async def _verify_mcp_configurations(self):
        """Verify MCP server configurations."""
        
        self.logger.info("πŸ”Œ Verifying 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:
                raise ApplicationError(
                    f"Missing MCP server configurations: {missing_servers}",
                    category=ErrorCategory.MCP_SERVER
                )
            
            # Validate each server configuration
            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:
                    raise ApplicationError(
                        f"MCP server {server_name} missing configuration: {missing_keys}",
                        category=ErrorCategory.MCP_SERVER
                    )
            
            self.components_status["mcp_servers"] = "configured"
            self.logger.info(f"βœ… MCP server configurations verified: {len(configured_servers)} servers")
            
        except Exception as e:
            self.components_status["mcp_servers"] = f"failed: {str(e)}"
            raise ApplicationError(
                f"MCP server configuration verification failed: {e}",
                category=ErrorCategory.MCP_SERVER
            )
    
    async def _initialize_orchestrator_components(self):
        """Initialize orchestrator components."""
        
        self.logger.info("🎼 Initializing orchestrator components...")
        
        try:
            # Import orchestrator components
            from orchestrator.mcp_client_manager import MCPClientManager
            from orchestrator.sse_manager import SSEManager
            from orchestrator.session_manager_simple import SessionManager
            from orchestrator.health_monitor import HealthMonitor
            from orchestrator.analysis_orchestrator import AnalysisOrchestrator
            
            # Test component initialization
            mcp_client = MCPClientManager()
            sse_manager = SSEManager()
            session_manager = SessionManager()
            health_monitor = HealthMonitor(mcp_client)
            orchestrator = AnalysisOrchestrator(mcp_client, sse_manager, session_manager)
            
            # Verify components have required methods
            required_methods = {
                'mcp_client': ['call_tool', 'get_server_health'],
                'sse_manager': ['broadcast_to_user', 'create_event_stream'],
                'session_manager': ['create_session', 'get_session'],
                'orchestrator': ['start_analysis', 'get_analysis_results']
            }
            
            components = {
                'mcp_client': mcp_client,
                'sse_manager': sse_manager,
                'session_manager': session_manager,
                'orchestrator': orchestrator
            }
            
            for component_name, methods in required_methods.items():
                component = components[component_name]
                missing_methods = [
                    method for method in methods
                    if not hasattr(component, method)
                ]
                
                if missing_methods:
                    raise ApplicationError(
                        f"Orchestrator component {component_name} missing methods: {missing_methods}",
                        category=ErrorCategory.SYSTEM
                    )
            
            self.components_status["orchestrator"] = "initialized"
            self.logger.info("βœ… Orchestrator components initialized")
            
        except Exception as e:
            self.components_status["orchestrator"] = f"failed: {str(e)}"
            raise ApplicationError(
                f"Orchestrator initialization failed: {e}",
                category=ErrorCategory.SYSTEM
            )
    
    async def _verify_streamlit_components(self):
        """Verify Streamlit components."""
        
        self.logger.info("🎨 Verifying Streamlit components...")
        
        try:
            # Test component imports
            components_to_test = [
                ('streamlit_app.components.auth', 'AuthManager'),
                ('streamlit_app.components.file_upload', 'FileUploadComponent'),
                ('streamlit_app.components.business_context', 'BusinessContextForm'),
                ('streamlit_app.components.progress_monitor', 'ProgressMonitor'),
                ('streamlit_app.components.results_viewer', 'ResultsViewer'),
                ('streamlit_app.utils.api_client', 'APIClient'),
                ('streamlit_app.utils.sse_client', 'SSEClient')
            ]
            
            import_failures = []
            
            for module_name, class_name in components_to_test:
                try:
                    module = __import__(module_name, fromlist=[class_name])
                    component_class = getattr(module, class_name)
                except Exception as e:
                    import_failures.append(f"{module_name}.{class_name}: {str(e)}")
            
            if import_failures:
                self.logger.warning(f"Streamlit component import issues: {import_failures}")
                # Don't fail initialization for Streamlit issues in non-UI contexts
            
            self.components_status["streamlit"] = "verified"
            self.logger.info("βœ… Streamlit components verified")
            
        except Exception as e:
            self.components_status["streamlit"] = f"failed: {str(e)}"
            # Don't fail system initialization for Streamlit issues
            self.logger.warning(f"Streamlit verification failed: {e}")
    
    async def _run_integration_tests(self):
        """Run basic integration tests."""
        
        self.logger.info("πŸ§ͺ Running integration tests...")
        
        try:
            # Test 1: Database CRUD operations
            await self._test_database_operations()
            
            # Test 2: Error handling system
            await self._test_error_handling()
            
            # Test 3: Monitoring system
            await self._test_monitoring_system()
            
            self.components_status["integration_tests"] = "passed"
            self.logger.info("βœ… Integration tests passed")
            
        except Exception as e:
            self.components_status["integration_tests"] = f"failed: {str(e)}"
            raise ApplicationError(
                f"Integration tests failed: {e}",
                category=ErrorCategory.SYSTEM
            )
    
    async def _test_database_operations(self):
        """Test basic database operations."""
        
        test_user_id = f"test_integration_{int(datetime.now().timestamp())}"
        
        async with get_database_connection() as conn:
            # Test insert
            await conn.execute(
                "INSERT INTO users (clerk_user_id, email) VALUES ($1, $2) ON CONFLICT DO NOTHING",
                test_user_id, f"{test_user_id}@test.com"
            )
            
            # Test select
            user_record = await conn.fetchrow(
                "SELECT * FROM users WHERE clerk_user_id = $1",
                test_user_id
            )
            
            if not user_record:
                raise Exception("Database CRUD test failed: record not found")
            
            # Test cleanup
            await conn.execute(
                "DELETE FROM users WHERE clerk_user_id = $1",
                test_user_id
            )
        
        self.logger.info("βœ… Database operations test passed")
    
    async def _test_error_handling(self):
        """Test error handling system."""
        
        try:
            # Generate a test error
            test_error = ValueError("Integration test error")
            
            # Handle the error
            error_info = await error_handler.handle_error(
                test_error,
                ErrorContext(
                    component="integration_test",
                    operation="test_error_handling"
                ),
                attempt_recovery=False
            )
            
            # Verify error was handled
            if not error_info or not error_info.error_id:
                raise Exception("Error handling test failed: no error info returned")
            
        except Exception as e:
            if "Integration test error" not in str(e):
                raise Exception(f"Error handling test failed: {e}")
        
        self.logger.info("βœ… Error handling test passed")
    
    async def _test_monitoring_system(self):
        """Test monitoring system."""
        
        # Test metric recording
        record_metric("integration_test.metric", 1.0, tags={"test": "true"})
        
        # Test timing operation
        async with time_operation("integration_test"):
            await asyncio.sleep(0.01)  # Small delay
        
        # Verify metrics were recorded
        latest_values = monitoring_system.metrics_collector.get_latest_values()
        
        if "integration_test.metric" not in latest_values:
            raise Exception("Monitoring test failed: metric not recorded")
        
        self.logger.info("βœ… Monitoring system test passed")
    
    async def shutdown_system(self):
        """Gracefully shutdown all system components."""
        
        self.logger.info("πŸ›‘ Starting system shutdown...")
        
        try:
            # Stop monitoring system
            await monitoring_system.stop_monitoring()
            
            self.logger.info("βœ… System shutdown completed")
            
        except Exception as e:
            self.logger.error(f"Error during system shutdown: {e}")
    
    def get_system_status(self) -> Dict[str, Any]:
        """Get comprehensive system status."""
        
        return {
            "initialization_complete": self.initialization_complete,
            "components_status": self.components_status,
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "monitoring_active": monitoring_system.monitoring_active
        }
    
    @asynccontextmanager
    async def system_context(self):
        """Context manager for system lifecycle."""
        
        try:
            # Initialize system
            success = await self.initialize_system()
            if not success:
                raise ApplicationError("System initialization failed")
            
            yield self
            
        finally:
            # Shutdown system
            await self.shutdown_system()


# Global integration coordinator instance
integration_coordinator = IntegrationCoordinator()