# -*- coding: utf-8 -*-
import mysql.connector
from netmiko import ConnectHandler
import re

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()

def test_olt():
    conn = mysql.connector.connect(**DB_CONFIG)
    cursor = conn.cursor(dictionary=True)
    # Tomamos la OLT "LA 40" o la primera que encuentre
    cursor.execute("SELECT id, nombre, ip_address, ssh_user, ssh_pass, ssh_port FROM olts LIMIT 1")
    olt = cursor.fetchone()
    conn.close()
    
    if not olt:
        print("No se encontraron OLTs en la base de datos.")
        return

    print(f"\n--- INICIANDO DIAGNSTICO EN: {olt['nombre']} ({olt['ip_address']}) ---")
    
    device = {
        'device_type': 'huawei_smartax',
        'host': olt['ip_address'],
        'username': olt['ssh_user'],
        'password': olt['ssh_pass'],
        'port': olt['ssh_port'],
        'global_delay_factor': 2
    }
    
    try:
        net_connect = ConnectHandler(**device)
        try: net_connect.enable()
        except: pass
        
        net_connect.send_command_timing("scroll 512")
        
        print("\n===============================================")
        print("         RAW OUTPUT (LO QUE ENVA LA OLT)      ")
        print("===============================================")
        raw_output = net_connect.send_command("display ont-srvprofile gpon all")
        print(raw_output)
        
        print("\n===============================================")
        print("     ANLISIS DEL REGEX (LO QUE LEE PYTHON)    ")
        print("===============================================")
        
        count = 0
        for line in raw_output.splitlines():
            line = line.strip()
            
            # Ignoramos lineas vacas o cabeceras de la tabla
            if not line or 'Profile-ID' in line or '---' in line:
                continue
                
            # Nuestro Regex actual
            m = re.search(r'^(\d+)\s+(.+)', line)
            
            if m:
                pid = int(m.group(1))
                pname = m.group(2).strip()
                print(f"[ OK ] -> ID: {pid: <4} | Nombre capturado: '{pname}'")
                count += 1
            else:
                print(f"[ ERROR / IGNORADA ] -> {line}")
        
        print(f"\nTotal de perfiles capturados por el script: {count}")
        net_connect.disconnect()
        
    except Exception as e:
        print(f"\nError de conexin: {e}")

if __name__ == "__main__":
    test_olt()
