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

Performance optimization initialization for MCP AI Data Scientist.

Initializes and configures all performance optimization systems.

"""

import asyncio
import logging
from typing import Dict, Any, Optional

from .caching import cache_manager
from .connection_pool import resource_manager
from .memory_manager import memory_manager
from .query_optimizer import supabase_optimizer
from .parallel_processor import parallel_processor
from .performance_monitor import performance_monitor
from .performance_config import (
    get_optimized_settings_for_environment,
    apply_performance_optimizations,
    get_config_for_environment
)

logger = logging.getLogger(__name__)


class PerformanceOptimizationManager:
    """Manages initialization and coordination of all performance optimization systems."""
    
    def __init__(self):
        self._initialized = False
        self._systems_started = False
        self._optimization_settings: Optional[Dict[str, Any]] = None
        self._performance_callbacks = []
    
    async def initialize(self, environment: str = None) -> Dict[str, Any]:
        """Initialize all performance optimization systems."""
        if self._initialized:
            logger.info("Performance optimization already initialized")
            return self._optimization_settings
        
        logger.info("Initializing performance optimization systems...")
        
        try:
            # Get optimized settings for current environment
            self._optimization_settings = get_optimized_settings_for_environment()
            env_config = get_config_for_environment(environment)
            
            # Apply environment-specific overrides
            self._apply_environment_config(env_config)
            
            # Configure individual systems
            await self._configure_cache_system()
            await self._configure_connection_pools()
            await self._configure_memory_management()
            await self._configure_query_optimization()
            await self._configure_parallel_processing()
            await self._configure_performance_monitoring()
            
            self._initialized = True
            logger.info("Performance optimization systems initialized successfully")
            
            return {
                'status': 'initialized',
                'settings': self._optimization_settings,
                'environment_config': env_config
            }
            
        except Exception as e:
            logger.error(f"Failed to initialize performance optimization: {e}")
            raise
    
    async def start_all_systems(self) -> Dict[str, Any]:
        """Start all performance optimization systems."""
        if not self._initialized:
            await self.initialize()
        
        if self._systems_started:
            logger.info("Performance optimization systems already started")
            return {'status': 'already_started'}
        
        logger.info("Starting performance optimization systems...")
        
        startup_results = {}
        
        try:
            # Start systems in order of dependency
            
            # 1. Start cache manager
            logger.info("Starting cache manager...")
            await cache_manager.start()
            startup_results['cache_manager'] = 'started'
            
            # 2. Start resource manager (connection pools)
            logger.info("Starting resource manager...")
            await resource_manager.start()
            startup_results['resource_manager'] = 'started'
            
            # 3. Start memory manager
            logger.info("Starting memory manager...")
            await memory_manager.start()
            startup_results['memory_manager'] = 'started'
            
            # 4. Start parallel processor
            logger.info("Starting parallel processor...")
            await parallel_processor.start()
            startup_results['parallel_processor'] = 'started'
            
            # 5. Start performance monitor (last, as it monitors other systems)
            logger.info("Starting performance monitor...")
            await performance_monitor.start()
            startup_results['performance_monitor'] = 'started'
            
            # Set up performance callbacks
            self._setup_performance_callbacks()
            
            self._systems_started = True
            logger.info("All performance optimization systems started successfully")
            
            return {
                'status': 'started',
                'systems': startup_results,
                'timestamp': asyncio.get_event_loop().time()
            }
            
        except Exception as e:
            logger.error(f"Failed to start performance optimization systems: {e}")
            # Attempt to stop any systems that were started
            await self.stop_all_systems()
            raise
    
    async def stop_all_systems(self) -> Dict[str, Any]:
        """Stop all performance optimization systems."""
        if not self._systems_started:
            logger.info("Performance optimization systems not started")
            return {'status': 'not_started'}
        
        logger.info("Stopping performance optimization systems...")
        
        shutdown_results = {}
        
        try:
            # Stop systems in reverse order
            
            # 1. Stop performance monitor
            try:
                await performance_monitor.stop()
                shutdown_results['performance_monitor'] = 'stopped'
            except Exception as e:
                logger.error(f"Error stopping performance monitor: {e}")
                shutdown_results['performance_monitor'] = f'error: {e}'
            
            # 2. Stop parallel processor
            try:
                await parallel_processor.stop()
                shutdown_results['parallel_processor'] = 'stopped'
            except Exception as e:
                logger.error(f"Error stopping parallel processor: {e}")
                shutdown_results['parallel_processor'] = f'error: {e}'
            
            # 3. Stop memory manager
            try:
                await memory_manager.stop()
                shutdown_results['memory_manager'] = 'stopped'
            except Exception as e:
                logger.error(f"Error stopping memory manager: {e}")
                shutdown_results['memory_manager'] = f'error: {e}'
            
            # 4. Stop resource manager
            try:
                await resource_manager.stop()
                shutdown_results['resource_manager'] = 'stopped'
            except Exception as e:
                logger.error(f"Error stopping resource manager: {e}")
                shutdown_results['resource_manager'] = f'error: {e}'
            
            # 5. Stop cache manager
            try:
                await cache_manager.stop()
                shutdown_results['cache_manager'] = 'stopped'
            except Exception as e:
                logger.error(f"Error stopping cache manager: {e}")
                shutdown_results['cache_manager'] = f'error: {e}'
            
            self._systems_started = False
            logger.info("Performance optimization systems stopped")
            
            return {
                'status': 'stopped',
                'systems': shutdown_results
            }
            
        except Exception as e:
            logger.error(f"Error during shutdown: {e}")
            return {
                'status': 'error',
                'error': str(e),
                'systems': shutdown_results
            }
    
    def _apply_environment_config(self, env_config: Dict[str, Any]):
        """Apply environment-specific configuration overrides."""
        if not env_config:
            return
        
        # Update cache settings
        if 'cache_max_size' in env_config:
            self._optimization_settings['cache'].max_size = env_config['cache_max_size']
        
        # Update connection settings
        if 'supabase_max_connections' in env_config:
            self._optimization_settings['connections'].supabase_max_connections = env_config['supabase_max_connections']
        
        # Update memory settings
        if 'memory_cleanup_threshold' in env_config:
            self._optimization_settings['memory'].cleanup_threshold = env_config['memory_cleanup_threshold']
        
        logger.info(f"Applied environment configuration overrides: {list(env_config.keys())}")
    
    async def _configure_cache_system(self):
        """Configure cache system with optimized settings."""
        cache_config = self._optimization_settings['cache']
        
        # Configure cache manager settings
        cache_manager.general_cache.max_size = cache_config.max_size
        cache_manager.general_cache.default_ttl = cache_config.default_ttl
        
        cache_manager.dataset_cache.max_datasets = cache_config.dataset_max_count
        cache_manager.dataset_cache.max_size_bytes = cache_config.dataset_max_size_mb * 1024 * 1024
        
        cache_manager.query_cache.cache.max_size = cache_config.query_max_entries
        cache_manager.query_cache.cache.default_ttl = cache_config.query_default_ttl
        
        cache_manager.model_cache.max_size = cache_config.model_max_count
        cache_manager.model_cache.default_ttl = cache_config.model_default_ttl
        
        logger.info(f"Configured cache system: max_size={cache_config.max_size}, dataset_max_size={cache_config.dataset_max_size_mb}MB")
    
    async def _configure_connection_pools(self):
        """Configure connection pools with optimized settings."""
        conn_config = self._optimization_settings['connections']
        
        # Connection pool settings will be applied when pools are created
        # This is handled in the resource manager initialization
        
        logger.info(f"Configured connection pools: supabase_max={conn_config.supabase_max_connections}, mcp_max={conn_config.mcp_max_connections}")
    
    async def _configure_memory_management(self):
        """Configure memory management with optimized settings."""
        memory_config = self._optimization_settings['memory']
        
        # Configure memory manager settings
        memory_manager._cleanup_threshold = memory_config.cleanup_threshold
        memory_manager.chunk_processor.chunk_size = memory_config.default_chunk_size
        memory_manager.chunk_processor.max_memory_mb = memory_config.max_memory_mb
        memory_manager.data_loader.memory_limit_mb = memory_config.loader_memory_limit_mb
        
        # Configure memory monitor thresholds
        memory_manager.monitor._thresholds['medium'] = memory_config.medium_pressure_threshold
        memory_manager.monitor._thresholds['high'] = memory_config.high_pressure_threshold
        memory_manager.monitor._thresholds['critical'] = memory_config.critical_pressure_threshold
        
        logger.info(f"Configured memory management: chunk_size={memory_config.default_chunk_size}, cleanup_threshold={memory_config.cleanup_threshold}%")
    
    async def _configure_query_optimization(self):
        """Configure query optimization with optimized settings."""
        query_config = self._optimization_settings['query']
        
        # Configure query optimizer settings
        supabase_optimizer._monitoring_enabled = query_config.enable_monitoring
        
        logger.info(f"Configured query optimization: monitoring={query_config.enable_monitoring}, caching={query_config.enable_query_caching}")
    
    async def _configure_parallel_processing(self):
        """Configure parallel processing with optimized settings."""
        parallel_config = self._optimization_settings['parallel']
        
        # Update worker pool configurations
        if 'cpu_intensive' in parallel_processor.worker_pools:
            pool = parallel_processor.worker_pools['cpu_intensive']
            if parallel_config.cpu_intensive_max_workers:
                pool.max_workers = parallel_config.cpu_intensive_max_workers
            pool.task_timeout = parallel_config.default_task_timeout
        
        if 'io_intensive' in parallel_processor.worker_pools:
            pool = parallel_processor.worker_pools['io_intensive']
            pool.max_workers = parallel_config.io_intensive_max_workers
            pool.task_timeout = parallel_config.default_task_timeout
        
        if 'general' in parallel_processor.worker_pools:
            pool = parallel_processor.worker_pools['general']
            pool.max_workers = parallel_config.general_max_workers
            pool.task_timeout = parallel_config.default_task_timeout
        
        logger.info(f"Configured parallel processing: cpu_workers={parallel_config.cpu_intensive_max_workers}, io_workers={parallel_config.io_intensive_max_workers}")
    
    async def _configure_performance_monitoring(self):
        """Configure performance monitoring with optimized settings."""
        monitor_config = self._optimization_settings['monitoring']
        
        # Configure performance monitor thresholds
        performance_monitor.thresholds.memory_warning = monitor_config.memory_warning_threshold
        performance_monitor.thresholds.memory_critical = monitor_config.memory_critical_threshold
        performance_monitor.thresholds.cache_hit_rate_warning = monitor_config.cache_hit_rate_warning
        performance_monitor.thresholds.cache_hit_rate_critical = monitor_config.cache_hit_rate_critical
        performance_monitor.thresholds.query_duration_warning = monitor_config.query_duration_warning
        performance_monitor.thresholds.query_duration_critical = monitor_config.query_duration_critical
        
        logger.info(f"Configured performance monitoring: interval={monitor_config.monitoring_interval}s, alerts={monitor_config.enable_alerts}")
    
    def _setup_performance_callbacks(self):
        """Set up performance monitoring callbacks."""
        # Memory pressure callback
        def memory_pressure_callback(memory_stats):
            if memory_stats.memory_pressure in ['high', 'critical']:
                logger.warning(f"Memory pressure detected: {memory_stats.memory_pressure} ({memory_stats.percent_used:.1f}%)")
                # Trigger cleanup
                asyncio.create_task(self._handle_memory_pressure(memory_stats))
        
        memory_manager.add_memory_callback(memory_pressure_callback)
        
        # Performance alert callback
        def performance_alert_callback(alert):
            logger.warning(f"Performance alert: {alert.severity.upper()} - {alert.message}")
            # Handle critical alerts
            if alert.severity == 'critical':
                asyncio.create_task(self._handle_critical_alert(alert))
        
        performance_monitor.add_alert_callback(performance_alert_callback)
        
        logger.info("Performance monitoring callbacks configured")
    
    async def _handle_memory_pressure(self, memory_stats):
        """Handle memory pressure situations."""
        try:
            if memory_stats.memory_pressure == 'critical':
                logger.warning("Handling critical memory pressure")
                
                # Aggressive cleanup
                await memory_manager.trigger_memory_cleanup(aggressive=True)
                
                # Clear caches
                cache_manager.general_cache.clear()
                cache_manager.dataset_cache.cleanup_chunks()
                
                # Force garbage collection
                import gc
                gc.collect()
                
            elif memory_stats.memory_pressure == 'high':
                logger.info("Handling high memory pressure")
                
                # Standard cleanup
                await memory_manager.trigger_memory_cleanup(aggressive=False)
                
                # Reduce cache sizes temporarily
                original_size = cache_manager.general_cache.max_size
                cache_manager.general_cache.max_size = int(original_size * 0.7)
                
        except Exception as e:
            logger.error(f"Error handling memory pressure: {e}")
    
    async def _handle_critical_alert(self, alert):
        """Handle critical performance alerts."""
        try:
            logger.critical(f"Handling critical alert: {alert.category} - {alert.message}")
            
            if alert.category == 'memory':
                await self._handle_memory_pressure(type('MemoryStats', (), {
                    'memory_pressure': 'critical',
                    'percent_used': alert.details.get('memory_percent', 95)
                })())
            
            elif alert.category == 'connection':
                # Handle connection pool issues
                pool_name = alert.details.get('pool_name')
                if pool_name and pool_name in resource_manager.pools:
                    logger.warning(f"Restarting connection pool: {pool_name}")
                    pool = resource_manager.pools[pool_name]
                    await pool.stop()
                    await pool.start()
            
            elif alert.category == 'parallel':
                # Handle parallel processing issues
                logger.warning("Restarting parallel processor due to critical alert")
                await parallel_processor.stop()
                await parallel_processor.start()
            
        except Exception as e:
            logger.error(f"Error handling critical alert: {e}")
    
    def get_system_status(self) -> Dict[str, Any]:
        """Get current status of all performance optimization systems."""
        return {
            'initialized': self._initialized,
            'systems_started': self._systems_started,
            'optimization_settings': self._optimization_settings is not None,
            'current_metrics': performance_monitor.get_current_metrics().to_dict() if performance_monitor.get_current_metrics() else None,
            'active_alerts': len(performance_monitor.get_active_alerts()),
            'system_health': performance_monitor.get_current_metrics().overall_health_score if performance_monitor.get_current_metrics() else None
        }
    
    async def get_comprehensive_report(self) -> Dict[str, Any]:
        """Get comprehensive performance report."""
        if not self._systems_started:
            return {'error': 'Performance systems not started'}
        
        try:
            # Collect reports from all systems
            cache_stats = cache_manager.get_comprehensive_stats()
            connection_stats = resource_manager.get_resource_summary()
            memory_report = memory_manager.get_memory_report()
            query_report = await supabase_optimizer.get_optimization_report()
            parallel_stats = parallel_processor.get_system_stats()
            performance_summary = performance_monitor.get_performance_summary()
            
            return {
                'timestamp': asyncio.get_event_loop().time(),
                'system_status': self.get_system_status(),
                'cache_statistics': cache_stats,
                'connection_statistics': connection_stats,
                'memory_report': memory_report,
                'query_optimization': query_report,
                'parallel_processing': parallel_stats,
                'performance_monitoring': performance_summary,
                'optimization_settings': self._optimization_settings
            }
            
        except Exception as e:
            logger.error(f"Error generating comprehensive report: {e}")
            return {'error': str(e)}


# Global performance optimization manager
performance_manager = PerformanceOptimizationManager()


# Convenience functions for easy initialization
async def initialize_performance_optimization(environment: str = None) -> Dict[str, Any]:
    """Initialize performance optimization systems."""
    return await performance_manager.initialize(environment)


async def start_performance_systems() -> Dict[str, Any]:
    """Start all performance optimization systems."""
    return await performance_manager.start_all_systems()


async def stop_performance_systems() -> Dict[str, Any]:
    """Stop all performance optimization systems."""
    return await performance_manager.stop_all_systems()


async def get_performance_report() -> Dict[str, Any]:
    """Get comprehensive performance report."""
    return await performance_manager.get_comprehensive_report()


def get_performance_status() -> Dict[str, Any]:
    """Get current performance system status."""
    return performance_manager.get_system_status()