#!/usr/bin/env python3
import sys
import mysql.connector
from netmiko import ConnectHandler
import re
import argparse

# --- CONFIGURACIN DE SEGURIDAD ---
# Usamos el usuario especfico que creamos, no root
import re, os
import re, os
import os
import os
import os
import os
import os
def __get_db_config_dynamic():
    cfg = {'host': '127.0.0.1', 'user': 'saas_admin', 'password': 'AdminSaaS2026!', 'database': 'adminolt_db'}
    for db_path in ['/var/www/html/db.php', '/root/Workspace360_paquete/db.php']:
        try:
            if os.path.exists(db_path):
                with open(db_path, 'r', encoding='utf-8', errors='ignore') as f:
                    for line in f:
                        line = line.strip()
                        if line.startswith('$host') and '=' in line:
                            part = line.split("'")[1] if "'" in line else line.split('"')[1]
                            cfg['host'] = '127.0.0.1' if part == 'localhost' else part
                        elif line.startswith('$user') and '=' in line:
                            cfg['user'] = line.split("'")[1] if "'" in line else line.split('"')[1]
                        elif line.startswith('$pass') and '=' in line:
                            cfg['password'] = line.split("'")[1] if "'" in line else line.split('"')[1]
                        elif line.startswith('$db') and '=' in line:
                            cfg['database'] = line.split("'")[1] if "'" in line else line.split('"')[1]
                break
        except: pass
    return cfg
DB_CONFIG = __get_db_config_dynamic()

# AJUSTAR CON TUS DATOS DE LA OLT HUAWEI
OLT_CONFIG = {
    'device_type': 'huawei_olt_la_40',
    'host': '172.32.0.2',  # <--- PONER IP DE TU OLT
    'username': 'smartoltusr',      # <--- USUARIO OLT
    'password': '',  # <--- PASSWORD OLT
    'port': 22,
    'global_delay_factor': 2 # Ayuda en conexiones lentas
}

def conectar_olt():
    try:
        return ConnectHandler(**OLT_CONFIG)
    except Exception as e:
        print(f"Error conectando a OLT: {e}")
        sys.exit(1)

def actualizar_onu(f, s, p, oid):
    print(f" Consultando ONU {f}/{s}/{p}/{oid}...")
    conn = conectar_olt()
    
    # 1. Obtener Estado y Causa
    # Comando Huawei: display ont info 0 1 0 0
    cmd = f"display ont info {f} {s} {p} {oid}"
    output = conn.send_command(cmd)
    
    estado = "OFFLINE"
    causa = "Unknown"
    
    # Lgica de parseo Huawei MA5600/5800
    if "Control flag           : active" in output:
        if "Run state              : online" in output:
            estado = "ONLINE"
            causa = "OK"
        else:
            # Buscar causa en el texto
            if "dying-gasp" in output.lower():
                estado = "SIN ENERGIA"
                causa = "Corte Energia (Dying Gasp)"
            elif "los" in output.lower() or "lof" in output.lower():
                estado = "CORTE FIBRA"
                causa = "Perdida de Seal (LOS)"
            else:
                estado = "OFFLINE"
                # Intentar extraer "Last down cause"
                match_cause = re.search(r'Last down cause\s+:\s+(.+)', output)
                if match_cause:
                    causa = match_cause.group(1).strip()
    
    # 2. Obtener Potencia (Solo si es relevante)
    potencia = -99.99
    if estado == "ONLINE" or estado == "ATENUACION":
        cmd_opt = f"display ont optical-info {f} {s} {p} {oid}"
        output_opt = conn.send_command(cmd_opt)
        
        # Regex para buscar: Rx optical power(dBm) : -22.34
        match_power = re.search(r'Rx optical power\(dBm\)\s+:\s+([-]?\d+\.\d+)', output_opt)
        if match_power:
            potencia = float(match_power.group(1))
            
            # Umbral de atenuacin (ajustable)
            if potencia < -27.00:
                estado = "ATENUACION"
    
    conn.disconnect()
    
    # 3. Guardar en BD
    try:
        db = mysql.connector.connect(**DB_CONFIG)
        cursor = db.cursor()
        sql = """UPDATE onus SET 
                 estado_actual=%s, potencia_rx=%s, ultima_causa_caida=%s 
                 WHERE frame=%s AND slot=%s AND port=%s AND onu_id=%s"""
        cursor.execute(sql, (estado, potencia, causa, f, s, p, oid))
        db.commit()
        db.close()
        print(f" [OK] Guardado: {estado} | {potencia}dBm | {causa}")
    except Exception as e:
        print(f" Error BD: {e}")

if __name__ == "__main__":
    # Argumentos desde PHP: python3 backend.py 0 1 0 5
    if len(sys.argv) < 5:
        print("Uso: python3 backend.py <frame> <slot> <port> <onu_id>")
        sys.exit(1)
        
    actualizar_onu(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])