import bencodepy
import hashlib
import os

# 📂 Dossier contenant les fichiers .torrent
TORRENT_FOLDER = "/var/www/html/hash_ygg/torrent/ygg_1080p/"
OUTPUT_FILE = "torrent_list.txt"

def get_torrent_info(torrent_file):
    """ Extrait le nom du fichier, le hash info et le lien magnet d'un .torrent """
    try:
        with open(torrent_file, "rb") as f:
            torrent_data = f.read()

        # Décoder le fichier torrent (Bencode)
        decoded_torrent = bencodepy.decode(torrent_data)

        # Vérifier si la clé "info" existe
        if b'info' not in decoded_torrent:
            return None, None, None

        # Encoder la partie "info" pour générer le hash
        info_encoded = bencodepy.encode(decoded_torrent[b'info'])
        info_hash = hashlib.sha1(info_encoded).hexdigest()

        # Récupérer le nom du fichier (si disponible)
        file_name = decoded_torrent[b'info'].get(b'name', b"Nom inconnu").decode('utf-8', errors='ignore')

        # Construire le lien magnet
        magnet_link = f"magnet:?xt=urn:btih:{info_hash}"

        return file_name, info_hash, magnet_link

    except Exception as e:
        print(f"❌ Erreur avec {torrent_file} : {e}")
        return None, None, None

def process_torrents():
    """ Scanne le dossier torrent/ et génère une liste des torrents avec leurs liens magnet """
    if not os.path.exists(TORRENT_FOLDER):
        print(f"❌ Erreur : Le dossier '{TORRENT_FOLDER}' n'existe pas.")
        return

    torrents_found = []
    count = 0

    for file in os.listdir(TORRENT_FOLDER):
        if file.endswith(".torrent"):
            file_path = os.path.join(TORRENT_FOLDER, file)
            file_name, info_hash, magnet = get_torrent_info(file_path)

            if file_name and info_hash and magnet:
                torrents_found.append(f"{file_name} | {info_hash} | {magnet}")
                count += 1
            
            # 🔥 Affiche l'avancement toutes les 100 torrents
            if count % 100 == 0:
                print(f"📌 {count} torrents traités...")

    # Sauvegarde dans un fichier
    if torrents_found:
        with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
            f.write("\n".join(torrents_found))
        print(f"✅ Liste générée dans '{OUTPUT_FILE}' ({len(torrents_found)} torrents trouvés)")
    else:
        print("❌ Aucun fichier .torrent valide trouvé.")

# 🚀 Exécution
if __name__ == "__main__":
    process_torrents()
