# -*- coding: utf-8 -*-

import os
import re
import requests
from urllib.parse import urlparse, unquote

M3U_FILE = "lista.m3u"       # il file m3u locale
ROOT_FOLDER = "copertinenuove"  # cartella principale dove creare sottocartelle

def estrai_logo_url(linea):
    match = re.search(r'tvg-logo="([^"]+\.jpg)"', linea)
    return match.group(1) if match else None

def nome_base_file(nome_file):
    # Prende la parte del nome prima di "_" o prima di un numero
    base = os.path.splitext(nome_file)[0]
    underscore_pos = base.find('_')
    numero_pos = re.search(r'\d', base)
    if underscore_pos != -1:
        base = base[:underscore_pos]
    elif numero_pos:
        base = base[:numero_pos.start()]
    return base.lower()  # meglio lowercase per uniformare

def scarica_file(url, cartella):
    nome_file_orig = os.path.basename(unquote(urlparse(url).path))
    nome_file = nome_file_orig
    file_path = os.path.join(cartella, nome_file)

    contatore = 1
    while os.path.exists(file_path):
        nome_senza_ext, ext = os.path.splitext(nome_file_orig)
        nome_file = f"{nome_senza_ext}_{contatore}{ext}"
        file_path = os.path.join(cartella, nome_file)
        contatore += 1

    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        with open(file_path, 'wb') as f:
            f.write(response.content)
        print(f"? Scaricato: {nome_file} in {cartella}/")
    except Exception as e:
        print(f"? Errore download {url}: {e}")

def main():
    gruppi_attori = {}

    try:
        with open(M3U_FILE, 'r', encoding='utf-8') as f:
            righe = f.readlines()

        # Trova tutte le righe EXTINF con 'XxX' (filtro del gruppo) e prendi i loghi jpg
        for linea in righe:
            if "#EXTINF" in linea and "XxX" in linea:
                if 'tvg-logo="' in linea:
                    url_logo = estrai_logo_url(linea)
                    if url_logo and "/xxx/" in url_logo:
                        nome_file = os.path.basename(unquote(urlparse(url_logo).path))
                        base = nome_base_file(nome_file)
                        gruppi_attori.setdefault(base, []).append(url_logo)

        # Crea la cartella principale
        os.makedirs(ROOT_FOLDER, exist_ok=True)

        # Per ogni attrice crea la cartella e scarica tutte le immagini
        for attore, urls in gruppi_attori.items():
            cartella_attore = os.path.join(ROOT_FOLDER, attore)
            os.makedirs(cartella_attore, exist_ok=True)
            print(f"\n?? Cartella attrice: {attore} - {len(urls)} immagini")
            for url in urls:
                scarica_file(url, cartella_attore)

    except Exception as e:
        print(f"? Errore durante l'esecuzione: {e}")

if __name__ == "__main__":
    main()
