#!/usr/bin/env python3
"""
PersonalTrade - Monitor de Consola para el Expert Collector (MT5 / MT4)
Versión: 1.0.0

Lee en vivo el archivo 'collector_state.json' generado por el EA en la carpeta común
de MetaTrader (%APPDATA%\\MetaQuotes\\Terminal\\Common\\Files).

Controles de teclado en tiempo real:
  [S] -> Vista Streaming (Dashboard vivo con tabla de instrumentos y estado)
  [L] -> Vista Logs (Secuencia de eventos y registros del EA)
  [Q] -> Salir
"""

import os
import sys
import time
import json
import argparse
from pathlib import Path
from datetime import datetime

# Colores ANSI
CLR_RESET   = "\033[0m"
CLR_BOLD    = "\033[1m"
CLR_DIM     = "\033[2m"
CLR_RED     = "\033[31m"
CLR_GREEN   = "\033[32m"
CLR_YELLOW  = "\033[33m"
CLR_BLUE    = "\033[34m"
CLR_MAGENTA = "\033[35m"
CLR_CYAN    = "\033[36m"
CLR_WHITE   = "\033[37m"
CLR_BG_BLUE = "\033[44m"

# Detección de teclado no bloqueante (Cross-platform)
def get_key_pressed():
    if os.name == 'nt':
        import msvcrt
        if msvcrt.kbhit():
            ch = msvcrt.getch()
            try:
                return ch.decode('utf-8').upper()
            except Exception:
                return ""
        return None
    else:
        import select
        dr, _, _ = select.select([sys.stdin], [], [], 0)
        if dr:
            ch = sys.stdin.read(1)
            return ch.upper()
        return None

def find_common_files_dir() -> Path:
    """Encuentra la carpeta común de MetaTrader según el sistema operativo."""
    if os.name == 'nt':
        appdata = os.environ.get('APPDATA', '')
        if appdata:
            p = Path(appdata) / "MetaQuotes" / "Terminal" / "Common" / "Files"
            if p.exists():
                return p
    # Fallback o Linux/Mac
    home = Path.home()
    candidates = [
        home / ".wine" / "drive_c" / "users" / os.environ.get("USER", "ricar") / "AppData" / "Roaming" / "MetaQuotes" / "Terminal" / "Common" / "Files",
        home / "AppData" / "Roaming" / "MetaQuotes" / "Terminal" / "Common" / "Files",
        Path("/tmp"),
        Path(".")
    ]
    for c in candidates:
        if c.exists():
            return c
    return Path(".")

def clear_screen():
    sys.stdout.write("\033[H\033[J")
    sys.stdout.flush()

def render_streaming_view(data: dict):
    lines = []
    lines.append(f"{CLR_BG_BLUE}{CLR_WHITE}{CLR_BOLD}  PERSONALTRADE CANDLE COLLECTOR - MONITOR EN VIVO v1.0.0  {CLR_RESET}")
    lines.append("")

    acc = data.get("account_number", "N/A")
    broker = data.get("broker", "N/A")
    version = data.get("version", "1.00")
    mode = data.get("mode", "INIT")
    server_time = data.get("server_time_gmt", "N/A")
    last_stream = data.get("last_stream_time", "N/A")
    last_count = data.get("last_stream_candles", 0)
    last_lat = data.get("last_stream_latency_ms", 0)
    tot_candles = data.get("total_candles_sent", 0)
    tot_batches = data.get("total_batches_sent", 0)

    # Color según el modo
    mode_color = CLR_GREEN if mode in ("STREAMING", "ALL_SYNCED") else (CLR_YELLOW if mode == "BATCH_SYNC" else CLR_CYAN)

    lines.append(f"  {CLR_BOLD}Cuenta:{CLR_RESET} {acc} ({broker})   {CLR_BOLD}Versión:{CLR_RESET} v{version}   {CLR_BOLD}Modo:{CLR_RESET} {mode_color}{mode}{CLR_RESET}")
    lines.append(f"  {CLR_BOLD}Hora GMT:{CLR_RESET} {server_time}   {CLR_BOLD}Total Velas:{CLR_RESET} {tot_candles:,} ({tot_batches:,} batches)")

    lat_color = CLR_GREEN if last_lat < 200 else (CLR_YELLOW if last_lat < 1000 else CLR_RED)
    lines.append(f"  {CLR_BOLD}Último Streaming:{CLR_RESET} {last_stream}  ({last_count} velas en {lat_color}{last_lat} ms{CLR_RESET})")

    # Timeframes al día
    up_tfs = data.get("up_to_date_timeframes", [])
    tfs_str = ", ".join(up_tfs) if up_tfs else "Ninguno"
    pending_tf = data.get("pending_timeframe", "NONE")
    pending_cur = data.get("pending_instrument_cursor", 0)
    tot_inst = data.get("total_instruments", 0)

    lines.append(f"  {CLR_BOLD}Timeframes al Día ({len(up_tfs)}/15):{CLR_RESET} {CLR_GREEN}{tfs_str}{CLR_RESET}")
    if pending_tf != "NONE":
        lines.append(f"  {CLR_BOLD}Reconciliando en Batch (seg 10-55):{CLR_RESET} {CLR_YELLOW}{pending_tf}{CLR_RESET} (Instrumento {pending_cur}/{tot_inst})")
    else:
        lines.append(f"  {CLR_BOLD}Reconciliación Batch:{CLR_RESET} {CLR_GREEN}Todos los timeframes al día{CLR_RESET}")

    lines.append("─" * 78)
    lines.append(f"{CLR_BOLD}{'SÍMBOLO':<28} {'ÚLTIMA VELA 1M':<22} {'ENVIADAS':<12} {'ESTADO'}{CLR_RESET}")
    lines.append("─" * 78)

    instruments = data.get("instruments", [])
    for inst in instruments[:28]:  # Mostrar hasta 28 en pantalla
        sym = inst.get("symbol", "")
        last_1m = inst.get("last_1m", "N/A")
        sent = inst.get("total_sent", 0)
        st = inst.get("status", "SYNCING")

        st_clr = CLR_GREEN if st == "STREAMING" else (CLR_YELLOW if st == "SYNCING" else CLR_RED)
        lines.append(f"{sym:<28} {last_1m:<22} {sent:<12,} {st_clr}{st}{CLR_RESET}")

    if len(instruments) > 28:
        lines.append(f"{CLR_DIM}... y {len(instruments) - 28} instrumentos adicionales activos.{CLR_RESET}")

    lines.append("─" * 78)
    lines.append(f"{CLR_BOLD}Comandos:{CLR_RESET} [{CLR_GREEN}S{CLR_RESET}] Streaming   [{CLR_CYAN}L{CLR_RESET}] Logs   [{CLR_RED}Q{CLR_RESET}] Salir")

    print("\n".join(lines))

def render_log_view(data: dict):
    lines = []
    lines.append(f"{CLR_BG_BLUE}{CLR_WHITE}{CLR_BOLD}  PERSONALTRADE CANDLE COLLECTOR - VISTA DE LOGS v1.0.0  {CLR_RESET}")
    lines.append("")

    acc = data.get("account_number", "N/A")
    broker = data.get("broker", "N/A")
    server_time = data.get("server_time_gmt", "N/A")
    lines.append(f"  {CLR_BOLD}Cuenta:{CLR_RESET} {acc} ({broker})   {CLR_BOLD}Hora GMT:{CLR_RESET} {server_time}")
    lines.append("─" * 78)

    recent_logs = data.get("recent_logs", [])
    if not recent_logs:
        lines.append("  (No hay registros de log disponibles aún)")
    else:
        for log_entry in recent_logs[-25:]:
            if "❌" in log_entry or "Error" in log_entry:
                lines.append(f"  {CLR_RED}{log_entry}{CLR_RESET}")
            elif "⚡" in log_entry or "STREAMING" in log_entry:
                lines.append(f"  {CLR_GREEN}{log_entry}{CLR_RESET}")
            elif "✅" in log_entry or "completad" in log_entry:
                lines.append(f"  {CLR_CYAN}{log_entry}{CLR_RESET}")
            elif "⚠️" in log_entry or "Aviso" in log_entry:
                lines.append(f"  {CLR_YELLOW}{log_entry}{CLR_RESET}")
            else:
                lines.append(f"  {log_entry}")

    lines.append("─" * 78)
    lines.append(f"{CLR_BOLD}Comandos:{CLR_RESET} [{CLR_GREEN}S{CLR_RESET}] Streaming   [{CLR_CYAN}L{CLR_RESET}] Logs   [{CLR_RED}Q{CLR_RESET}] Salir")

    print("\n".join(lines))

def resolve_state_file(arg_file: str, arg_account: str) -> Path:
    """Encuentra inteligentemente el archivo de telemetría adecuado."""
    common_dir = find_common_files_dir()

    # 1. Si el usuario pasó un archivo explícito
    if arg_file:
        p = Path(arg_file)
        if p.is_file():
            return p
        if (common_dir / arg_file).is_file():
            return common_dir / arg_file
        return p

    # 2. Si el usuario especificó una cuenta o palabra clave (--account / -a)
    if arg_account:
        target = arg_account.strip().lower()
        candidates = list(common_dir.glob("collector_state*.json"))
        # Búsqueda por coincidencia en el nombre del archivo
        for c in candidates:
            if target in c.name.lower():
                return c
        # Búsqueda por contenido del archivo (account_number o broker)
        for c in candidates:
            try:
                with open(c, "r", encoding="utf-8") as f:
                    d = json.load(f)
                    acc = str(d.get("account_number", "")).lower()
                    brk = str(d.get("broker", "")).lower()
                    if target in acc or target in brk:
                        return c
            except Exception:
                pass
        return common_dir / f"collector_state_{arg_account}.json"

    # 3. Detección automática en la carpeta común
    candidates = [c for c in common_dir.glob("collector_state*.json") if c.is_file()]

    if len(candidates) == 0:
        return common_dir / "collector_state.json"

    if len(candidates) == 1:
        return candidates[0]

    # Filtrar el archivo genérico 'collector_state.json' si existen versiones específicas por cuenta
    specific_candidates = [c for c in candidates if c.name not in ("collector_state.json", "collector_state_mt4.json")]
    if len(specific_candidates) >= 1:
        candidates = specific_candidates

    if len(candidates) == 1:
        return candidates[0]

    # Ordenar por fecha de modificación (el más reciente primero)
    candidates.sort(key=lambda x: x.stat().st_mtime, reverse=True)

    print(f"\n{CLR_BOLD}📡 PersonalTrade - Múltiples terminales colectoras detectadas:{CLR_RESET}\n")
    for idx, cand in enumerate(candidates, 1):
        meta_str = ""
        try:
            with open(cand, "r", encoding="utf-8") as f:
                d = json.load(f)
                acc = d.get("account_number", "?")
                brk = d.get("broker", "?")
                mode = d.get("mode", "?")
                meta_str = f"Cuenta: {acc} | Broker: {brk} | Modo: {mode}"
        except Exception:
            meta_str = "Lectura pendiente"

        mtime = datetime.fromtimestamp(cand.stat().st_mtime).strftime("%H:%M:%S")
        print(f"  {CLR_CYAN}[{idx}]{CLR_RESET} {CLR_BOLD}{cand.name}{CLR_RESET} ({meta_str} | Activo: {mtime})")

    print(f"\nSeleccione terminal [1-{len(candidates)}] o presione ENTER para la más reciente (1): ", end="", flush=True)
    try:
        choice = input().strip()
        if choice.isdigit() and 1 <= int(choice) <= len(candidates):
            selected = candidates[int(choice) - 1]
        else:
            selected = candidates[0]
    except Exception:
        selected = candidates[0]

    print(f"-> Conectando a {selected.name}...\n")
    time.sleep(1.0)
    return selected

def main():
    parser = argparse.ArgumentParser(description="Monitor de Consola para el EA Colector MT5/MT4")
    parser.add_argument("--file", "-f", type=str, default=None, help="Ruta o nombre del archivo de estado (ej: collector_fxpro.json)")
    parser.add_argument("--account", "-a", type=str, default=None, help="Número de cuenta o broker para filtrar (ej: 514889456, deriv)")
    parser.add_argument("--mode", "-m", type=str, choices=["S", "L"], default="S", help="Modo inicial (S=Streaming, L=Log)")
    args = parser.parse_args()

    state_path = resolve_state_file(args.file, args.account)

    print(f"Buscando archivo de telemetría en: {state_path}")
    active_mode = args.mode.upper()

    # Configuración de terminal en Unix
    old_settings = None
    if os.name != 'nt':
        import termios
        import tty
        try:
            old_settings = termios.tcgetattr(sys.stdin)
            tty.setcbreak(sys.stdin.fileno())
        except Exception:
            pass

    try:
        last_mtime = 0
        last_data = {}

        while True:
            # Capturar teclas presionadas
            key = get_key_pressed()
            if key == 'Q':
                break
            elif key == 'S':
                active_mode = 'S'
            elif key == 'L':
                active_mode = 'L'

            if state_path.exists():
                try:
                    mtime = state_path.stat().st_mtime
                    if mtime != last_mtime or key is not None:
                        with open(state_path, "r", encoding="utf-8") as f:
                            last_data = json.load(f)
                        last_mtime = mtime

                        clear_screen()
                        if active_mode == 'S':
                            render_streaming_view(last_data)
                        else:
                            render_log_view(last_data)
                except Exception as e:
                    pass
            else:
                clear_screen()
                print(f"⏳ Esperando que el EA cree el archivo en:\n   {state_path}\n\nPresione [Q] para salir...")

            time.sleep(0.3)

    except KeyboardInterrupt:
        pass
    finally:
        if old_settings is not None and os.name != 'nt':
            import termios
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
        print("\nMonitor detenido.")

if __name__ == "__main__":
    main()
