from datetime import datetime, timedelta
import pytz
import unicodedata
import re

TZ = pytz.timezone("America/Tijuana")

ALIASES = {
    "aguilas": ["aguilas", "mexicali"],
    "naranjeros": ["naranjeros", "hermosillo"],
    "yaquis": ["yaquis", "obregon"],
    "tomateros": ["tomateros", "culiacan"],
    "mayos": ["mayos", "navojoa"],
    "caneros": ["caneros", "mochis"],
    "algodoneros": ["algodoneros", "guasave"],
    "venados": ["venados", "mazatlan"],
    "charros": ["charros", "jalisco"],
    "jaguares": ["jaguares", "nayarit"]
}

def normalizar(valor):
    texto = ''.join(
        c for c in unicodedata.normalize('NFD', str(valor).lower())
        if unicodedata.category(c) != 'Mn'
    )
    return re.sub(r'[^a-z0-9]', '', texto)

def identificar(nombre):
    n = normalizar(nombre)
    encontrados = [
        slug for slug, aliases in ALIASES.items()
        if any(normalizar(a) in n for a in aliases)
    ]
    return encontrados[0] if len(encontrados) == 1 else None

def observar(epg, ahora=None):
    ahora = ahora or datetime.now(TZ)
    if ahora.tzinfo is None:
        ahora = TZ.localize(ahora)

    response = epg.get("response", {})
    resultados = {}

    for seccion in ("games", "prevGames", "nextGames"):
        for juego in response.get(seccion, []) or []:
            away = identificar(juego.get("awayTeamShort", ""))
            home = identificar(juego.get("homeTeamShort", ""))

            if not away or not home or away == home:
                continue

            try:
                inicio = datetime.fromisoformat(
                    juego["localFullDate"].replace("Z", "+00:00")
                )
                if inicio.tzinfo is None:
                    inicio = TZ.localize(inicio)
                else:
                    inicio = inicio.astimezone(TZ)
            except (ValueError, KeyError, TypeError):
                continue

            estado = juego.get("gameStatus")

            if estado == 1:
                decision = "PERMITIR_EN_VIVO"
            elif estado == 2:
                decision = "FINAL_REQUIERE_ESTADO_PERSISTENTE"
            elif estado == 0:
                if ahora < inicio - timedelta(minutes=10):
                    decision = "PREVIO_CERRADO"
                elif ahora <= inicio + timedelta(minutes=30):
                    decision = "VENTANA_PREPARACION"
                else:
                    decision = "ESTADO_NO_CONFIRMADO"
            else:
                decision = "ESTADO_DESCONOCIDO"

            for equipo in (away, home):
                resultados.setdefault(equipo, []).append({
                    "partido": away + "_vs_" + home,
                    "inicio": inicio.isoformat(),
                    "estado": estado,
                    "decision": decision
                })

    return resultados
