"""Verifica, SIN GUARDAR NADA, qué nombre devuelve el sistema para cada RUT del Excel
y lo compara con la columna NOMBRE. Útil para detectar RUT/nombres cruzados.

Uso:
    python verificar_ruts.py
    python verificar_ruts.py --excel "PRUEBA AUTOM. LIC. MED. 2.0.xlsx"
"""
import argparse
from datetime import date
from config import EXCEL_PATH, normaliza
from excel_reader import leer_licencias
from automation import LicenciaBot


def mismos_tokens(a, b):
    """True si ambos nombres tienen exactamente el mismo conjunto de palabras
    (ignora orden, tildes y mayúsculas)."""
    ta = set(normaliza(a).split())
    tb = set(normaliza(b).split())
    return bool(ta) and ta == tb


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--excel", default=EXCEL_PATH)
    ap.add_argument("--headed", action="store_true")
    args = ap.parse_args()

    licencias = leer_licencias(args.excel)
    hoy = date.today().strftime("%d-%m-%Y")
    print(f"Verificando {len(licencias)} RUT del Excel: {args.excel}\n")

    ok = cruzados = no_carga = 0
    with LicenciaBot(headless=not args.headed) as bot:
        bot.login()
        print(f"{'Fila':>4}  {'RUT':<13} {'NOMBRE (Excel)':<32} {'NOMBRE (Sistema)':<34} Estado")
        print("-" * 100)
        for lic in licencias:
            fila = lic.get("_fila_excel")
            rut = lic["rut"]
            nombre_excel = lic.get("nombre", "")
            fecha = lic.get("fecha_emision") or hoy
            nombre_sistema = bot.consultar_funcionario(rut, fecha)

            if not nombre_sistema:
                estado = "NO CARGA (RUT o período inválido)"
                no_carga += 1
            elif mismos_tokens(nombre_excel, nombre_sistema):
                estado = "OK (coincide)"
                ok += 1
            else:
                estado = "*** CRUZADO (no coincide) ***"
                cruzados += 1

            print(f"{fila:>4}  {rut:<13} {nombre_excel[:31]:<32} {nombre_sistema[:33]:<34} {estado}")

    print("-" * 100)
    print(f"Resumen: {ok} coinciden · {cruzados} cruzados · {no_carga} no cargan")


if __name__ == "__main__":
    main()
