"""
BLOQUE 6: Infrastructure & Generation Integration
Integración de todos los módulos T216-T235 con el MCP Server
"""

from typing import Dict, Any, Optional
import os
import sys

# Importar todos los módulos del Bloque 6
from .cloud.export_system_report import export_system_report
from .logs.persistent_logs import get_log_manager, log_event, get_logs
from .cloud.performance_watchdog import (
    start_performance_monitoring, 
    get_performance_status,
    stop_performance_monitoring
)
from .cloud.health_checks import (
    start_health_checks,
    get_health_status,
    run_health_check
)
from .cloud.stats_visualizer import get_generation_stats
from .dashboard.web_dashboard import start_dashboard, stop_dashboard, get_dashboard_url
from .cloud.auto_improve import auto_improve_set
from .cloud.dj_set_mapper import generate_dj_set
from .cloud.tracklist_cue_generator import generate_tracklist
from .cloud.blueprint_multilayer import get_generation_manifest
from .cloud.performance_renderer import render_performance_video
from .cloud.stem_meta_tags import export_stem_mixdown
from .cloud.vst_plugin_support import configure_vst_layer
from .cloud.library_daemon import scan_sample_library, get_sample_library_stats
from .cloud.set_profile_csv import generate_set_profile_csv
from .cloud.diversity_dashboard import get_diversity_memory_stats, get_coverage_wheel_report
from .cloud.latency_tester import run_latency_test, run_stress_test
from .cloud.websocket_runtime import (
    start_websocket_runtime,
    get_websocket_status,
    broadcast_event
)
from .m4l_integration.m4l_ml_devices import (
    configure_m4l_ml_layer,
    get_m4l_capabilities
)
from .cloud.dj_4hour_test import (
    start_4hour_dj_test,
    get_4hour_test_status,
    stop_4hour_test
)


class Block6Integration:
    """
    Integrador principal del BLOQUE 6.
    
    Proporciona acceso unificado a todas las funcionalidades T216-T235.
    """
    
    VERSION = "2.0.0"
    BLOCK = "T216-T235"
    
    def __init__(self):
        self.components = {
            'reports': True,
            'logs': True,
            'performance_watchdog': False,
            'health_checks': False,
            'dashboard': False,
            'websocket': False,
            'library_daemon': False
        }
    
    def start_all_services(self) -> Dict[str, Any]:
        """Inicia todos los servicios del Bloque 6."""
        results = {}
        
        # Iniciar health checks
        results['health_checks'] = start_health_checks(interval_seconds=60)
        self.components['health_checks'] = True
        
        # Iniciar dashboard
        results['dashboard'] = start_dashboard(port=8765)
        self.components['dashboard'] = True
        
        # Iniciar WebSocket runtime
        results['websocket'] = start_websocket_runtime()
        self.components['websocket'] = True
        
        # Escanear librería
        results['library_scan'] = scan_sample_library()
        self.components['library_daemon'] = True
        
        return {
            'status': 'services_started',
            'block': self.BLOCK,
            'version': self.VERSION,
            'results': results,
            'dashboard_url': get_dashboard_url()
        }
    
    def get_full_status(self) -> Dict[str, Any]:
        """Obtiene estado completo del sistema."""
        return {
            'block': self.BLOCK,
            'version': self.VERSION,
            'timestamp': __import__('datetime').datetime.now().isoformat(),
            'components': self.components,
            'health': get_health_status() if self.components['health_checks'] else None,
            'performance': get_performance_status() if self.components['performance_watchdog'] else None,
            'websocket': get_websocket_status() if self.components['websocket'] else None,
            'diversity': get_diversity_memory_stats(),
            'library': get_sample_library_stats(),
            'dashboard_url': get_dashboard_url() if self.components['dashboard'] else None
        }
    
    def run_dj_set_generation(self, duration_hours: float = 2.0,
                           style_evolution: str = 'progressive') -> Dict[str, Any]:
        """Genera set DJ completo."""
        return generate_dj_set(duration_hours, style_evolution)
    
    def export_full_report(self, format: str = 'json') -> Dict[str, Any]:
        """Exporta reporte completo del sistema."""
        return export_system_report(format=format)


def get_block6_summary() -> Dict[str, Any]:
    """
    Obtiene resumen del BLOQUE 6.
    
    Returns:
        Resumen completo de implementación T216-T235
    """
    modules = {
        'T216': 'export_system_report - Reportes JSON/CSV/Markdown',
        'T217': 'persistent_logs - Almacenamiento perenne de logs',
        'T218': 'performance_watchdog - Monitoreo 3-8 horas',
        'T219': 'health_checks - Health checks programados',
        'T220': 'stats_visualizer - Generador visual de estadísticas',
        'T221': 'web_dashboard - Panel Web MCP wrapper',
        'T222': 'auto_improve - Regeneración de loops',
        'T223': 'dj_set_mapper - Mapeo DJ set multihour',
        'T224': 'tracklist_cue_generator - Tracklists con CUE points',
        'T225': 'blueprint_multilayer - Blueprint multi-capas',
        'T226': 'performance_renderer - Video/GIF de performance',
        'T227': 'stem_meta_tags - Tags Meta en Stems',
        'T228': 'vst_plugin_support - Soporte Plugins VST',
        'T229': 'library_daemon - Escaneo background librería',
        'T230': 'set_profile_csv - Set Profile CSV pre-show',
        'T231': 'diversity_dashboard - Estadísticas de diversidad',
        'T232': 'latency_tester - Testing 100 clips concurrentes',
        'T233': 'websocket_runtime - Refactoring a WebSockets',
        'T234': 'm4l_ml_devices - Max for Live ML devices',
        'T235': 'dj_4hour_test - Prueba DJ 4 horas (MILESTONE)'
    }
    
    directories = {
        'cloud': 'Módulos cloud (reportes, performance, blueprints)',
        'logs': 'Sistema de logs persistentes',
        'dashboard': 'Panel web y visualización',
        'm4l_integration': 'Integración Max for Live'
    }
    
    return {
        'block': 'BLOQUE 6',
        'range': 'T216-T235',
        'version': '2.0.0',
        'modules_implemented': len(modules),
        'modules': modules,
        'directories': directories,
        'status': 'COMPLETED',
        'compilation': 'All modules compiled successfully'
    }


# Instancia global
_block6: Optional[Block6Integration] = None

def get_block6_integration() -> Block6Integration:
    """Obtiene instancia del integrador del Bloque 6."""
    global _block6
    if _block6 is None:
        _block6 = Block6Integration()
    return _block6


if __name__ == '__main__':
    # Test de integración
    print("BLOQUE 6 - Infrastructure & Generation")
    print("=" * 60)
    
    summary = get_block6_summary()
    print(f"\nSummary: {summary['block']} ({summary['range']})")
    print(f"Status: {summary['status']}")
    print(f"Modules: {summary['modules_implemented']}")
    
    print("\nModules:")
    for t_code, description in summary['modules'].items():
        print(f"  {t_code}: {description}")
    
    print("\nDirectories:")
    for dir_name, description in summary['directories'].items():
        print(f"  cloud/{dir_name}/: {description}")
    
    print("\n" + "=" * 60)
    print("BLOQUE 6 Implementation Complete!")
