"""
Interfaz de línea de comandos para el Sistema de Lectura Automática de Medidores.

Este módulo implementa la interfaz de usuario basada en línea de comandos
para interactuar con el backend del sistema.

Desarrolladores:
- Para añadir nuevos comandos, agregue nuevas funciones de manejo y actualice la lógica en run_cli()
- Para modificar el comportamiento de los comandos existentes, ajuste las funciones correspondientes
"""

from prompt_toolkit import PromptSession
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.formatted_text import HTML
from colorama import Fore, Style

def run_cli(backend):
    """
    Ejecuta la interfaz de línea de comandos.

    Args:
        backend (MeterReadingBackend): Instancia del backend del sistema.
    """
    session = PromptSession()
    
    print(f"{Fore.MAGENTA}{Style.BRIGHT}Bienvenido al Sistema de Lectura Automática de Medidores{Style.RESET_ALL}")
    print(f"{Fore.CYAN}Use 'help' para ver los comandos disponibles.{Style.RESET_ALL}")
    
    while True:
        try:
            with patch_stdout():
                command = session.prompt(HTML('<ansigreen>AMI Backend></ansigreen> '))
            
            if command.startswith("add"):
                handle_add_command(backend, command)
            elif command == "list":
                backend.list_connections()
            elif command.startswith("remove"):
                handle_remove_command(backend, command)
            elif command == "status":
                backend.status()
            elif command == "help":
                show_help()
            elif command == "exit":
                break
            else:
                print(f"{Fore.RED}Comando no reconocido. Use 'help' para ver los comandos disponibles.{Style.RESET_ALL}")

        except KeyboardInterrupt:
            continue
        except EOFError:
            break

    print(f"{Fore.MAGENTA}{Style.BRIGHT}Saliendo del programa...{Style.RESET_ALL}")

def handle_add_command(backend, command):
    """
    Maneja el comando para añadir una nueva conexión.

    Args:
        backend (MeterReadingBackend): Instancia del backend del sistema.
        command (str): Comando completo ingresado por el usuario.
    """
    parts = command.split()
    if len(parts) < 5:
        print(f"{Fore.YELLOW}Uso: add <host> <port> <mode> <meter_type> [--interrogation] [--frequency <seconds>]{Style.RESET_ALL}")
    else:
        host, port, mode, meter_type = parts[1:5]
        interrogation = "--interrogation" in parts
        frequency = 60
        if "--frequency" in parts:
            frequency = int(parts[parts.index("--frequency") + 1])
        backend.add_connection(host, int(port), mode, meter_type, interrogation, frequency)

def handle_remove_command(backend, command):
    """
    Maneja el comando para eliminar una conexión existente.

    Args:
        backend (MeterReadingBackend): Instancia del backend del sistema.
        command (str): Comando completo ingresado por el usuario.
    """
    parts = command.split()
    if len(parts) != 2:
        print(f"{Fore.YELLOW}Uso: remove <index>{Style.RESET_ALL}")
    else:
        try:
            index = int(parts[1])
            backend.remove_connection(index)
        except ValueError:
            print(f"{Fore.RED}Error: El índice debe ser un número entero.{Style.RESET_ALL}")

def show_help():
    """Muestra la lista de comandos disponibles y su descripción."""
    print(f"{Fore.CYAN}Comandos disponibles:{Style.RESET_ALL}")
    print(f"  {Fore.GREEN}add <host> <port> <mode> <meter_type> [--interrogation] [--frequency <seconds>]{Style.RESET_ALL}: Añade una nueva conexión")
    print(f"  {Fore.GREEN}list{Style.RESET_ALL}: Lista todas las conexiones activas")
    print(f"  {Fore.GREEN}remove <index>{Style.RESET_ALL}: Elimina una conexión por su índice")
    print(f"  {Fore.GREEN}status{Style.RESET_ALL}: Muestra el estado de todas las conexiones")
    print(f"  {Fore.GREEN}help{Style.RESET_ALL}: Muestra esta lista de comandos")
    print(f"  {Fore.GREEN}exit{Style.RESET_ALL}: Cierra el programa")
