"""
Módulo principal del sistema - MVP v1.0

Punto de entrada del sistema que coordina:
- Inicialización de componentes
- Procesamiento en tiempo real
- Procesamiento estadístico
- Interfaz de comandos
"""

import argparse
import logging
import threading
import time
import coloredlogs
from datetime import datetime

from config.settings import LOG_LEVEL
from processors.realtime.analyzer import RealtimeAnalyzer
from processors.statistics.processor import StatisticsProcessor
from cli.menu import run_menu

logger = logging.getLogger(__name__)

def setup_logging():
    """Configura el sistema de logging"""
    coloredlogs.install(
        level=LOG_LEVEL,
        fmt='%(asctime)s [%(levelname)s] %(message)s'
    )
    return logging.getLogger(__name__)

def main():
    logger = setup_logging()
    
    parser = argparse.ArgumentParser(description='Sistema de Monitoreo de Sensores IoT')
    parser.add_argument('db_name', help='Nombre de la base de datos')
    parser.add_argument('-v', '--verbose', action='store_true', help='Modo verbose')
    parser.add_argument('--realtime-only', action='store_true', help='Solo proceso en tiempo real')
    parser.add_argument('--stats-only', action='store_true', help='Solo proceso estadístico')
    args = parser.parse_args()

    try:
        # Inicializar procesadores según argumentos
        realtime_proc = None
        stats_proc = None

        if not args.stats_only:
            realtime_proc = RealtimeAnalyzer(args.db_name)
            if args.verbose:
                realtime_proc.toggle_verbose()

        if not args.realtime_only:
            stats_proc = StatisticsProcessor(args.db_name)
            if args.verbose:
                stats_proc.toggle_verbose()

        # Crear threads para los procesadores
        threads = []
        
        if realtime_proc:
            realtime_thread = threading.Thread(
                target=realtime_proc.run,
                name="RealtimeAnalyzer"
            )
            realtime_thread.daemon = True
            threads.append(realtime_thread)
            logger.info("Analizador en tiempo real inicializado")

        if stats_proc:
            stats_thread = threading.Thread(
                target=stats_proc.run,
                name="StatisticsProcessor"
            )
            stats_thread.daemon = True
            threads.append(stats_thread)
            logger.info("Procesador estadístico inicializado")

        # Iniciar threads
        for thread in threads:
            thread.start()
            # Pequeña pausa entre threads
            time.sleep(0.5)

        logger.info("Sistema iniciado")
        
        # Ejecutar menú
        run_menu(realtime_proc, stats_proc)

    except KeyboardInterrupt:
        logger.info("Interrupción de usuario recibida")
    except Exception as e:
        logger.error(f"Error en sistema: {e}", exc_info=True)
    finally:
        # Detener procesadores
        if realtime_proc:
            realtime_proc.stop()
        if stats_proc:
            stats_proc.stop()
        
        # Esperar threads
        for thread in threads:
            thread.join(timeout=5)
            
        logger.info("Sistema finalizado")

if __name__ == "__main__":
    main()