"""
Módulo de comandos CLI - MVP v1.0

Implementa la interfaz de línea de comandos del sistema:
- Procesamiento de comandos de usuario
- Visualización de estado
- Control del sistema
"""

import os
import logging
from datetime import datetime
from prettytable import PrettyTable

logger = logging.getLogger(__name__)

class CommandProcessor:
    def __init__(self, realtime_proc=None, stats_proc=None):
        self.realtime = realtime_proc
        self.stats = stats_proc
        self.running = True
        self.commands = {
            'X': self._exit_system,
            'V': self._toggle_verbose,
            'D': self._toggle_debug,
            'S': self._show_status,
            'M': self._show_measurements,
            'L': self._clear_screen,
            'C': self._show_configurations,
            'A': self._show_active_alarms,
            'P': self._show_period_status
        }

    def start(self):
        """Inicia el procesador de comandos"""
        while self.running:
            try:
                self._show_menu()
                cmd = input("\nComando: ").strip().upper()
                self._process_command(cmd)
            except EOFError:
                break
            except Exception as e:
                logger.error(f"Error procesando comando: {e}")

    def _show_menu(self):
        """Muestra el menú de comandos disponibles"""
        print("\n=== Sistema de Monitoreo ===")
        estados = []
        if any(proc and proc.verbose for proc in [self.realtime, self.stats]):
            estados.append("VERBOSE")
        if any(proc and proc.debug for proc in [self.realtime, self.stats]):
            estados.append("DEBUG")
            
        print(f"Estado: {' | '.join(estados) or 'NORMAL'}")
        print("\nComandos disponibles:")
        print("  X - Salir")
        print("  V - Toggle modo Verbose")
        print("  D - Toggle modo Debug")
        print("  S - Mostrar estado")
        print("  M - Mostrar mediciones")
        print("  L - Limpiar pantalla")
        print("  C - Mostrar configuraciones")
        print("  A - Mostrar alarmas activas")
        print("  P - Estado de períodos")

    def _process_command(self, cmd):
        """Procesa un comando de usuario"""
        if cmd in self.commands:
            self.commands[cmd]()
        else:
            print("Comando no reconocido")

    def _exit_system(self):
        """Detiene el sistema"""
        self.running = False
        if self.realtime:
            self.realtime.stop()
        if self.stats:
            self.stats.stop()
        print("Deteniendo sistema...")

    def _toggle_verbose(self):
        """Cambia el modo verbose"""
        if self.realtime:
            self.realtime.toggle_verbose()
        if self.stats:
            self.stats.toggle_verbose()

    def _toggle_debug(self):
        """Cambia el modo debug"""
        if self.realtime:
            self.realtime.toggle_debug()
        if self.stats:
            self.stats.toggle_debug()

    def _clear_screen(self):
        """Limpia la pantalla"""
        os.system('cls' if os.name == 'nt' else 'clear')

    def _show_status(self):
        """Muestra el estado del sistema"""
        print("\n=== Estado del Sistema ===")
        
        if self.realtime:
            metrics = self.realtime.get_metrics()
            print("\nProceso en Tiempo Real:")
            print(f"  Mediciones procesadas: {metrics['processed_measurements']}")
            print(f"  Desvíos detectados: {metrics['detected_deviations']}")
            print(f"  Alarmas generadas: {metrics['generated_alarms']}")
        
        if self.stats:
            metrics = self.stats.get_metrics()
            print("\nProceso Estadístico:")
            print(f"  Registros generados: {metrics['generated_records']}")
            print(f"  Períodos activos: {metrics['active_periods']}")

    def _show_measurements(self):
        """Muestra las mediciones actuales"""
        if not self.stats:
            print("Procesador estadístico no disponible")
            return

        print("\n=== Mediciones Actuales ===")
        metrics = self.stats.get_metrics()
        for period in metrics['current_periods']:
            print(f"\nEntrada {period['dmac']}:")
            print(f"  Período actual: {period['period_start']}")

    def _show_configurations(self):
        """Muestra la tabla de configuraciones"""
        if not self.realtime:
            print("Procesador en tiempo real no disponible")
            return

        print("\n=== Configuraciones de Sensores ===")
        table = PrettyTable()
        table.field_names = [
            "Sistema", "Entrada", "Val. Min", "Val. Max", 
            "T.Max (seg)", "Factor", "Genera Alarma"
        ]
        
        configs = self.realtime.get_configs()
        for key, config in sorted(configs.items()):
            table.add_row([
                key[0],                    # Sistema
                key[1],                    # Entrada
                config['vMin1'],           # Valor mínimo
                config['vMax1'],           # Valor máximo
                config['tMax1'],           # Tiempo máximo
                config.get('factor', 1),   # Factor
                'Sí' if config['generaAlarma'] else 'No'
            ])
            
        print(table)

    def _show_active_alarms(self):
        """Muestra las alarmas activas"""
        if not self.realtime:
            print("Procesador en tiempo real no disponible")
            return

        print("\n=== Alarmas Activas ===")
        table = PrettyTable()
        table.field_names = [
            "Sistema", "Entrada", "Valor", "Estado", "Fecha"
        ]
        
        alarms = self.realtime.get_active_alarms()
        for alarm in alarms:
            table.add_row([
                alarm['idSistema'],
                alarm['idEntrada'],
                f"{alarm['valor']:.1f}",
                alarm['idEstado'],
                alarm['fecha'].strftime("%Y-%m-%d %H:%M:%S")
            ])
            
        print(table)

    def _show_period_status(self):
        """Muestra el estado de los períodos actuales"""
        if not self.stats:
            print("Procesador estadístico no disponible")
            return

        print("\n=== Estado de Períodos ===")
        table = PrettyTable()
        table.field_names = [
            "DMAC", "Entrada", "Inicio Período", "Mediciones"
        ]
        
        metrics = self.stats.get_metrics()
        for period in metrics['current_periods']:
            table.add_row([
                period['dmac'],
                period['idEntrada'],
                period['period_start'],
                period.get('measurements', 0)
            ])
            
        print(table)