import requests
import re

URL_FUENTE = "http://wb9xxxwh.k34zyer.xyz/get.php?username=Syrge0913T&password=Pwpetpafe121&type=m3u_plus&output=mpegts"
ARCHIVO_SALIDA = "/mnt/nvme/iptv/lista_filtrada.m3u"

# ---------------------------------------------------------------
# GRUPOS POR PAIS - busca en group-title
# ---------------------------------------------------------------
GRUPOS_PAIS = {
    "ES":     (["SPAIN"],                                          "Espana"),
    "PL":     (["POLAND", "POLSKA", "POLISH"],                    "Polonia"),
    "UK":     (["UNITED KINGDOM"],                                 "United Kingdom"),
    "LATINO": (["LATINO", "LATAM", "LATIN", "MEXICO", "ARGENTINA",
                "COLOMBIA", "CHILE", "PERU", "VENEZUELA"],         "Latino"),
}

# ---------------------------------------------------------------
# FILTRO FUTBOL - busca en group-title O en tvg-name
# Captura canales deportivos de CUALQUIER pais
# ---------------------------------------------------------------
PALABRAS_FUTBOL_GRUPO = [
    "FOOTBALL", "FUTBOL", "SOCCER", "SPORT", "SPORTS", "DEPORTES",
    "LALIGA", "LA LIGA", "PREMIER", "CHAMPIONS", "UEFA", "FIFA",
    "SERIE A", "BUNDESLIGA", "LIGUE 1", "EREDIVISIE",
    "DAZN", "BEIN", "ESPN", "EUROSPORT",
    "SKY SPORT", "BT SPORT", "TNT SPORT", "ELEVEN SPORT",
    "MOVISTAR LIGA", "MOVISTAR SPORT",
    "GOL TV", "GOL PLAY",
    "SETANTA",          # Setanta Sports
    "GO3",              # Go3 Sports
    "ARENA SPORT",
    "SPORT KLUB",
    "SWISS SPORT",      # canales suizos
    "RTS SPORT",        # suiza publica
    "SRF SPORT",        # suiza aleman
]

PALABRAS_FUTBOL_NOMBRE = [
    "FOOTBALL", "FUTBOL", "SOCCER",
    "LALIGA", "LA LIGA", "PREMIER",
    "CHAMPIONS", "UEFA", "FIFA",
    "SETANTA", "GO3 SPORT",
    "BEIN SPORT", "BT SPORT", "SKY SPORT",
    "TNT SPORT", "ELEVEN SPORT",
    "ARENA SPORT", "SPORT KLUB",
    "RTS SPORT", "SRF SPORT",
]

# ---------------------------------------------------------------
# FILTRO FÓRMULA 1
# ---------------------------------------------------------------
PALABRAS_F1_GRUPO = [
    "FORMULA 1", "FORMULA1", "FORMULA ONE", "F1",
    "MOTORSPORT", "MOTOR SPORT", "MOTORSPORTS",
    "F1 TV", "F1TV",
    "SKY SPORTS F1", "SKY F1",
    "F1 LIVE",
]

PALABRAS_F1_NOMBRE = [
    "FORMULA 1", "FORMULA1", "FORMULA ONE", "F1",
    "MOTORSPORT", "MOTOR SPORT",
    "F1 TV", "F1TV",
    "SKY SPORTS F1", "SKY F1",
]

# ---------------------------------------------------------------
# FILTRO ADULT (se camuflarán en grupo "Motor")
# ---------------------------------------------------------------
PALABRAS_ADULT_GRUPO = [
    "ADULT", "XXX", "PENTHOUSE", "PLAYBOY", "EROTIC", "EROTICA",
    "BLUE HUSTLER", "HUSTLER", "DORCEL", "HOT NEWS",
    "BABELAND", "VIVID", "WICKED", "PRIVATE",
    "SEX", "PORNO", "PORN", "HARDCORE",
]

PALABRAS_ADULT_NOMBRE = [
    "ADULT", "XXX", "PENTHOUSE", "PLAYBOY", "EROTIC",
    "HUSTLER", "DORCEL", "VIVID", "WICKED", "PRIVATE",
    "SEX", "PORNO", "PORN", "HARDCORE",
]
# <<< NUEVO

RE_GROUP   = re.compile(r'(group-title=")[^"]*(")', re.IGNORECASE)
RE_TVGNAME = re.compile(r'tvg-name="([^"]*)', re.IGNORECASE)

def detectar_pais(group_upper):
    for region, (palabras, nombre) in GRUPOS_PAIS.items():
        for p in palabras:
            if p.upper() in group_upper:
                return region, nombre
    return None, None

def es_futbol(line_upper):
    for p in PALABRAS_FUTBOL_GRUPO:
        if p.upper() in line_upper:
            return True
    m = RE_TVGNAME.search(line_upper)
    if m:
        tvgname = m.group(1).upper()
        for p in PALABRAS_FUTBOL_NOMBRE:
            if p.upper() in tvgname:
                return True
    return False

def es_f1(line_upper):
    for p in PALABRAS_F1_GRUPO:
        if p.upper() in line_upper:
            return True
    m = RE_TVGNAME.search(line_upper)
    if m:
        tvgname = m.group(1).upper()
        for p in PALABRAS_F1_NOMBRE:
            if p.upper() in tvgname:
                return True
    return False

# <<< NUEVO
def es_adult(line_upper):
    for p in PALABRAS_ADULT_GRUPO:
        if p.upper() in line_upper:
            return True
    m = RE_TVGNAME.search(line_upper)
    if m:
        tvgname = m.group(1).upper()
        for p in PALABRAS_ADULT_NOMBRE:
            if p.upper() in tvgname:
                return True
    return False

def normalizar_grupo(line_str, nombre_grupo):
    return RE_GROUP.sub(r'\g<1>' + nombre_grupo + r'\g<2>', line_str)

def filtrar():
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) VLC/3.0.18'}
    conteo_pais   = {r: 0 for r in GRUPOS_PAIS}
    conteo_futbol = 0
    conteo_f1     = 0
    conteo_adult  = 0  # <<< NUEVO

    try:
        print("Iniciando descarga y filtrado...")
        with requests.get(URL_FUENTE, stream=True, timeout=60, headers=headers) as r:
            r.raise_for_status()

            with open(ARCHIVO_SALIDA, "w", encoding="utf-8") as f:
                f.write("#EXTM3U\n")

                pending_extinf  = None   # linea #EXTINF guardada temporalmente
                total = 0

                for line in r.iter_lines():
                    if not line:
                        continue

                    try:
                        line_str = line.decode('utf-8').strip()
                    except UnicodeDecodeError:
                        line_str = line.decode('latin-1').strip()

                    if line_str.startswith("#EXTINF"):
                        pending_extinf = line_str   # guardamos para decidir luego

                    elif line_str.startswith("#EXTVLCOPT") and pending_extinf:
                        pass  # la guardamos junto al canal cuando llegue la URL

                    elif not line_str.startswith("#") and pending_extinf:
                        # Esta es la URL del canal - ahora decidimos si lo incluimos
                        lu = pending_extinf.upper()
                        m_group = RE_GROUP.search(pending_extinf)
                        group_upper = m_group.group(0).upper() if m_group else ""

                        region, nombre_pais = detectar_pais(group_upper)
                        futbol = es_futbol(lu)
                        f1     = es_f1(lu)
                        adult  = es_adult(lu)  # <<< NUEVO

                        if region:
                            # Canal de pais conocido -> carpeta del pais
                            linea = normalizar_grupo(pending_extinf, nombre_pais)
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_pais[region] += 1
                            total += 1

                        if futbol and not region:
                            # Canal deportivo de otro pais -> carpeta Futbol
                            linea = normalizar_grupo(pending_extinf, "Futbol")
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_futbol += 1
                            total += 1

                        elif futbol and region:
                            # Canal ya en carpeta de pais pero tambien es futbol
                            # -> lo duplicamos en carpeta Futbol
                            linea = normalizar_grupo(pending_extinf, "Futbol")
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_futbol += 1
                            total += 1

                        # FÓRMULA 1: mismo esquema que futbol
                        if f1 and not region:
                            linea = normalizar_grupo(pending_extinf, "F1")
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_f1 += 1
                            total += 1

                        elif f1 and region:
                            # Duplicar en carpeta F1
                            linea = normalizar_grupo(pending_extinf, "F1")
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_f1 += 1
                            total += 1

                        # ADULT: se camuflan en grupo "Motor"
                        if adult and not region:
                            linea = normalizar_grupo(pending_extinf, "Motor")
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_adult += 1
                            total += 1

                        elif adult and region:
                            # Duplicar en carpeta Motor
                            linea = normalizar_grupo(pending_extinf, "Motor")
                            f.write(linea + "\n")
                            f.write(line_str + "\n")
                            conteo_adult += 1
                            total += 1

                        pending_extinf = None

                    else:
                        pending_extinf = None

        print("-" * 45)
        print(f"EXITO: Lista guardada en {ARCHIVO_SALIDA}")
        print(f"Total de entradas: {total}")
        print("-" * 45)
        for region, cant in conteo_pais.items():
            nombre = GRUPOS_PAIS[region][1]
            print(f"  {nombre:20s}: {cant} canales")
        print(f"  {'Futbol':20s}: {conteo_futbol} canales")
        print(f"  {'F1':20s}: {conteo_f1} canales")
        print(f"  {'Adult (Motor)':20s}: {conteo_adult} canales")  # <<< NUEVO
        print("-" * 45)

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

if __name__ == "__main__":
    filtrar()