# -*- coding: utf-8 -*-
import asyncio
import json
import csv
import re
from datetime import datetime


URL_CONSUMO    = "https://autogestion-empresas.claro.com.ar/sites/launchpad#zcrm0204gestionesgeneraleslineas-Display&/"
ID_CUENTA      = "application-zcrm0204gestionesgeneraleslineas-Display-component---Menu--input_cuenta"
ID_LINEA_INPUT = "application-zcrm0204gestionesgeneraleslineas-Display-component---Menu--inpLinea-inner"

_vermas_clickeado = False

async def seleccionar_cuenta(page, numero_cuenta):
    # Verificar si la cuenta ya esta seleccionada
    input_cuenta = page.locator(f"#{ID_CUENTA}-inner")
    valor_actual = await input_cuenta.get_attribute("value")

    if valor_actual and numero_cuenta in valor_actual:
        print(f"  Cuenta ya seleccionada: {valor_actual}")
        return True

    print(f"Abriendo dropdown cuenta...")
    boton_dropdown = await page.query_selector(f"#{ID_CUENTA} .sapMInputBaseIconContainer")
    if boton_dropdown:
        await boton_dropdown.click()
    else:
        await page.click(f"#{ID_CUENTA}")

    await asyncio.sleep(2)

    selectores = [
        "[role='option']",
        "[role='listitem']",
        ".sapMSelectListItem",
        ".sapMListTbl tr",
        ".sapMLIBContent",
    ]

    for selector in selectores:
        items = await page.query_selector_all(selector)
        if items:
            print(f"  Encontrado con '{selector}': {len(items)} items")
            for item in items:
                texto = await item.inner_text()
                if numero_cuenta in texto:
                    await item.click()
                    await asyncio.sleep(2)
                    print(f"  Cuenta seleccionada: {texto.strip()}")
                    return True
            break

    # Si no encontro nada verificar si ya hay valor en el campo
    valor = await input_cuenta.get_attribute("value")
    if valor:
        print(f"  Cuenta en campo: {valor} (usando valor existente)")
        return True

    print(f"  Cuenta {numero_cuenta} no encontrada")
    await page.screenshot(path="error_cuenta.png")
    return False


async def seleccionar_linea(page, numero_cuenta, numero_linea, primera_vez=False):
    global _vermas_clickeado

    if primera_vez:
        print(f"Navegando a Gestiones en Lineas...")
        await page.goto(URL_CONSUMO, wait_until="domcontentloaded")
        await asyncio.sleep(3)
        ok = await seleccionar_cuenta(page, numero_cuenta)
        if not ok:
            return False

    print(f"Ingresando linea: {numero_linea}")
    input_linea = page.locator(f"#{ID_LINEA_INPUT}")

    await input_linea.click()
    await asyncio.sleep(0.5)
    await page.keyboard.press("Control+a")
    await page.keyboard.press("Delete")
    await asyncio.sleep(0.5)

    await page.keyboard.type(numero_linea, delay=150)
    await asyncio.sleep(2)

    print("  Esperando lista de sugerencias...")
    selectores_sug = [
        ".sapMSuggestionItem",
        ".sapMSuggPopover li",
        "[role='option']",
        ".sapMLIB",
        ".sapMSLI",
    ]

    items = []
    for intento in range(20):
        for selector in selectores_sug:
            items = await page.query_selector_all(selector)
            if items:
                break
        if items:
            break
        await asyncio.sleep(0.5)

    if not items:
        await page.screenshot(path="debug_linea.png")
        print("  Sin sugerencias - ver debug_linea.png")
        return False

    print(f"  Lista aparecio con {len(items)} items")

    # Clic en ver mas solo la primera vez
    if not _vermas_clickeado:
        boton_vermas = await page.query_selector("#btnGrowing")
        if boton_vermas:
            print("  Haciendo clic en Ver mas...")
            await boton_vermas.click()
            await asyncio.sleep(4)

            for intento in range(10):
                items_nuevos = []
                for selector in selectores_sug:
                    items_nuevos = await page.query_selector_all(selector)
                    if items_nuevos and len(items_nuevos) > len(items):
                        break
                if items_nuevos and len(items_nuevos) > len(items):
                    items = items_nuevos
                    print(f"  Lista completa: {len(items)} items")
                    break
                await asyncio.sleep(0.5)

            _vermas_clickeado = True
            print("  Ver mas clickeado, no se volvera a clickear")
    else:
        print("  Ver mas ya fue clickeado anteriormente")

    # Buscar la linea en la lista completa
    for item in items:
        texto = await item.inner_text()
        if numero_linea in texto:
            await page.evaluate("""el => {
                el.dispatchEvent(new MouseEvent('mousedown', {bubbles: true}));
                el.dispatchEvent(new MouseEvent('mouseup',   {bubbles: true}));
                el.dispatchEvent(new MouseEvent('click',     {bubbles: true}));
            }""", item)
            await asyncio.sleep(1)
            print(f"  Linea seleccionada: {texto.strip()[:60]}")
            return True

    print(f"  Linea {numero_linea} no encontrada en la lista")
    return False

async def extraer_bloques(page, numero_linea):
    print(f"Navegando a Saldos y Consumos...")

    selectores_menu = [
        ".sapMSLITitle:has-text('Saldos y Consumos')",
        ".sapMText:has-text('Saldos y Consumos')",
        "li:has-text('Saldos y Consumos')",
        ".sapMNavItem:has-text('Saldos y Consumos')",
        "[title='Saldos y Consumos']",
    ]

    clickeado = False
    for selector in selectores_menu:
        try:
            elemento = page.locator(selector).first
            visible = await elemento.is_visible()
            if visible:
                await elemento.click()
                await asyncio.sleep(3)
                print(f"  Menu clickeado con: {selector}")
                clickeado = True
                break
        except:
            continue

    if not clickeado:
        try:
            await page.locator("text=Saldos y Consumos").filter(has=page.locator(":visible")).first.click()
            await asyncio.sleep(3)
            clickeado = True
            print("  Menu clickeado con filtro visible")
        except:
            await page.screenshot(path="debug_menu.png")
            print("  No se pudo clickear menu - ver debug_menu.png")
            return []

    bloques = await page.query_selector_all(".zBloqueBordeRedondeado")
    print(f"Bloques encontrados: {len(bloques)}")

    resultados = []

    for bloque in bloques:
        try:
            titulo_el     = await bloque.query_selector(".sapMTitle span")
            pct_el        = await bloque.query_selector(".sapSuiteRMCInsideLabel")
            detalle_el    = await bloque.query_selector(".sapMObjectIdentifierText span")
            renovacion_el = await bloque.query_selector("bdi")

            titulo     = await titulo_el.inner_text()     if titulo_el     else "Sin titulo"
            porcentaje = await pct_el.inner_text()        if pct_el        else "N/A"
            detalle    = await detalle_el.inner_text()    if detalle_el    else "N/A"
            renovacion = await renovacion_el.inner_text() if renovacion_el else "N/A"

            parsed = parsear_detalle(detalle, titulo)

            item = {
                "fecha"           : datetime.now().strftime("%Y-%m-%d %H:%M"),
                "linea"           : numero_linea,
                "titulo"          : titulo,
                "porcentaje_usado": porcentaje,
                "detalle"         : detalle,
                "usado"           : parsed["usado"],
                "total"           : parsed["total"],
                "unidad"          : parsed["unidad"],
                "renovacion"      : renovacion,
            }
            resultados.append(item)
            print(f"  {titulo}: {porcentaje} | {detalle} | usado={parsed['usado']} {parsed['unidad']} | {renovacion}")

        except Exception as e:
            print(f"  Error en bloque: {e}")

    return resultados

def guardar_resultados_archivo(resultados):
    if not resultados:
        print("Sin resultados para guardar")
        return

    # JSON
    with open("consumo_todas.json", "w", encoding="utf-8") as f:
        json.dump(resultados, f, ensure_ascii=False, indent=2)

    # CSV
    with open("consumo_todas.csv", "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=resultados[0].keys())
        writer.writeheader()
        writer.writerows(resultados)

    print(f"\nListo. {len(resultados)} registros guardados.")
    print(f"  -> consumo_todas.json")
    print(f"  -> consumo_todas.csv")

def parsear_detalle(detalle, titulo):
    """
    Entrada:  '2276.27 Min de 10000 Min'
    Salida:   { 'usado': 2276.27, 'total': 10000.0, 'unidad': 'Min' }
    """
    if not detalle or detalle == "N/A":
        return {"usado": None, "total": 0, "unidad": "N/A"}

    # Buscar patron: NUMERO UNIDAD de NUMERO UNIDAD
    match = re.search(r"([\d,.]+)\s*(\w+)\s+de\s+([\d,.]+)\s*(\w+)", detalle)
    if match:
        usado  = int(float(match.group(1).replace(",", ".")))
        unidad = match.group(2)
        total  = float(match.group(3).replace(",", "."))
        return {"usado": usado, "total": total, "unidad": unidad}

    return {"usado": 0, "total": 0, "unidad": "N/A"}


def verificar_alertas(resultados, callback_alerta):
    """
    Revisa cada resultado y llama a callback_alerta
    cuando el campo usado llega a 0
    """
    for item in resultados:
        if item["usado"] == 0 and item["unidad"] != "N/A":
            print(f"  ALERTA: linea {item['linea']} - {item['titulo']} llegó a 0")
            callback_alerta(item)
