#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
             T411 RÉTRO — SCRIPT D'UPLOAD AUTOMATISÉ SEEDBOX & CLI
=============================================================================
Génère le .torrent avec announce T411, scanne MediaInfo, crée le NFO rétro,
téléverse la release sur T411 et injecte le .torrent dans qBittorrent / Transmission.

Usage :
  python3 t411_uploader.py "/chemin/vers/film_ou_dossier" --passkey VOTRE_PASSKEY
  python3 t411_uploader.py "/chemin/vers/film.mkv" --passkey VOTRE_PASSKEY --client qbittorrent
=============================================================================
"""

import sys
import os
import argparse
import hashlib
import json
import subprocess
import mimetypes
import urllib.request
import urllib.parse
from pathlib import Path

T411_API_URL = "https://t411.org/api_upload.php"
T411_ANNOUNCE = "https://t411.org/announce.php"

# =============================================================================
# 1. AUTO-DÉTECTION FINE DES CATÉGORIES & SOUS-CATÉGORIES T411
# =============================================================================
def normalize_category(cat_input):
    if not cat_input:
        return None
    c = cat_input.strip().lower()
    mapping = {
        'films': 'Films', 'film': 'Films', 'movie': 'Films', 'movies': 'Films', 'cinema': 'Films',
        'series': 'Séries', 'séries': 'Séries', 'série': 'Séries', 'serie': 'Séries', 'tv': 'Séries',
        'musique': 'Musique', 'music': 'Musique', 'audio': 'Musique', 'son': 'Musique', 'album': 'Musique', 'albums': 'Musique',
        'ebooks': 'Ebooks', 'ebook': 'Ebooks', 'livres': 'Ebooks', 'livre': 'Ebooks', 'presse': 'Ebooks', 'bd': 'Ebooks', 'comics': 'Ebooks',
        'jeux': 'Jeux Vidéo', 'jeu': 'Jeux Vidéo', 'jeux video': 'Jeux Vidéo', 'jeux vidéo': 'Jeux Vidéo', 'game': 'Jeux Vidéo', 'games': 'Jeux Vidéo',
        'logiciels': 'Applications', 'logiciel': 'Applications', 'applications': 'Applications', 'application': 'Applications', 'app': 'Applications', 'apps': 'Applications', 'soft': 'Applications', 'softs': 'Applications',
        'animes': 'Animes & Mangas', 'anime': 'Animes & Mangas', 'manga': 'Animes & Mangas', 'mangas': 'Animes & Mangas',
        '3d': 'Création & Modèles 3D',
        'adultes': 'Adultes (+18)', 'adulte': 'Adultes (+18)', 'xxx': 'Adultes (+18)', '18': 'Adultes (+18)', '+18': 'Adultes (+18)'
    }
    return mapping.get(c, cat_input.strip())

def default_sub_for_category(cat, target_path=None):
    if cat == 'Musique':
        if target_path:
            name_lower = target_path.name.lower()
            if any(k in name_lower for k in ['flac', 'lossless', '24-bit', 'hi-res', 'wav', 'alac']):
                return 'FLAC Lossless'
        return 'MP3 & Audio'
    if cat == 'Films':
        return '1080p HD'
    if cat == 'Séries':
        return 'Saisons Complètes'
    if cat in ['Ebooks', 'Ebooks & Presse']:
        return 'Romans & Littérature'
    if cat in ['Jeux Vidéo', 'Jeux']:
        return 'PC'
    if cat in ['Applications', 'Logiciels']:
        return 'Windows'
    if cat == 'Adultes (+18)':
        return 'Films & Scènes XXX (1080p / 720p HD)'
    return 'Autre'

def detect_t411_category(path_obj):
    name = path_obj.name.lower()
    ext = path_obj.suffix.lower()

    # Détection Adultes (+18) / XXX / Hentai
    adult_keywords = ['xxx', 'hentai', 'doujinshi', 'porn', 'jav', 'brazzers', 'eroge', 'uncensored', '+18', 'nude', 'fetish', 'vixen', 'blacked']
    if any(k in name for k in adult_keywords):
        if any(k in name for k in ['doujinshi', 'manga']):
            return ('Adultes (+18)', 'Doujinshi & Mangas Hentai (Scans HD)')
        if any(k in name for k in ['hentai', 'eroge', 'anime']):
            return ('Adultes (+18)', 'Hentai & Animation Adultes (Japonais / Non-Censuré)')
        if any(k in name for k in ['8k', '6k', 'vr', '4320p']):
            return ('Adultes (+18)', 'Films & Scènes XXX (4K / 6K / 8K VR)')
        return ('Adultes (+18)', 'Films & Scènes XXX (1080p / 720p HD)')

    # Analyse des extensions si dossier
    dir_exts = {}
    audio_files_count = 0
    video_files_count = 0
    ebook_files_count = 0
    lossless_count = 0

    if path_obj.is_dir():
        scanned = 0
        for p in path_obj.rglob('*'):
            if p.is_file():
                scanned += 1
                e = p.suffix.lower()
                dir_exts[e] = dir_exts.get(e, 0) + 1
                if e in ['.flac', '.alac', '.wav', '.ape', '.dff', '.dsf']:
                    audio_files_count += 1
                    lossless_count += 1
                elif e in ['.mp3', '.m4a', '.aac', '.ogg', '.opus', '.wma']:
                    audio_files_count += 1
                elif e in ['.mkv', '.mp4', '.avi', '.ts', '.m2ts', '.mov', '.wmv']:
                    video_files_count += 1
                elif e in ['.epub', '.pdf', '.cbr', '.cbz', '.mobi', '.azw3']:
                    ebook_files_count += 1
                if scanned >= 300:
                    break

    # Détection Musique prioritaire si fichiers audio dominants ou mots-clés musicaux
    music_keywords = ['mp3', '320kbps', 'flac', 'lossless', 'alac', 'discography', 'discographie', 'album', 'ost', 'soundtrack', 'cbr', 'vbr', 'hi-res', '24bit', '24-bit', 'cd rip', 'eac', 'single', 'ep', 'remastered', 'webrip-audio']
    if (audio_files_count > 0 and video_files_count == 0) or any(k in name for k in music_keywords) or ext in ['.flac', '.alac', '.wav', '.ape', '.mp3', '.m4a', '.aac', '.ogg', '.opus', '.wma']:
        if ext in ['.flac', '.alac', '.wav', '.ape'] or lossless_count > 0 or any(k in name for k in ['flac', 'lossless', '24bit', '24-bit', 'hi-res', 'alac']):
            return ('Musique', 'FLAC Lossless')
        return ('Musique', 'MP3 & Audio')

    # Détection Ebooks
    if ext in ['.epub', '.pdf', '.cbr', '.cbz', '.mobi', '.azw3'] or (ebook_files_count > 0 and video_files_count == 0):
        if ext in ['.cbr', '.cbz'] or any(k in name for k in ['bd', 'comic', 'manga']):
            return ('Ebooks', 'BDs & Comics')
        if any(k in name for k in ['presse', 'magazine', 'journal', 'revue']):
            return ('Ebooks', 'Presse & Magazines')
        return ('Ebooks', 'Romans & Littérature')

    # Détection Jeux Vidéo
    game_keywords = ['fitgirl', 'dodi', 'skidrow', 'codex', 'repack', 'crack', 'gog', 'steamrip', 'reloaded']
    if any(k in name for k in game_keywords) or (ext == '.iso' and any(k in name for k in ['game', 'jeu', 'v1.', 'v2.'])) or any(k in dir_exts for k in ['.nsp', '.xci', '.rom', '.cia']):
        if any(k in name for k in ['switch', 'ps4', 'ps5', 'xbox', 'rom', 'cia', 'nsp']):
            return ('Jeux Vidéo', 'Consoles & Émulation')
        return ('Jeux Vidéo', 'PC')

    # Détection Applications
    if ext in ['.dmg', '.pkg'] or 'mac' in name:
        return ('Applications', 'Mac OS')
    if ext in ['.exe', '.msi'] or any(k in name for k in ['setup', 'windows', 'x64', 'patch', 'keygen']):
        return ('Applications', 'Windows')
    if ext in ['.deb', '.rpm', '.tar.gz', '.appimage'] or 'linux' in name:
        return ('Applications', 'Linux')

    # Détection Séries TV
    series_regex_hints = ['s0', 's1', 's2', 's3', 's4', 'season', 'saison', 'integrale', 'complete.series']
    if any(k in name for k in series_regex_hints) or any(f"s{i:02d}" in name for i in range(1, 30)):
        if any(f"e{i:02d}" in name for i in range(1, 50)):
            return ('Séries', 'Épisodes Individuels')
        return ('Séries', 'Saisons Complètes')

    # Détection Films (par résolution & type)
    if any(k in name for k in ['4320p', '8k', '6k', '3160p']):
        return ('Films', '8K & 6K UHD / VR')
    if any(k in name for k in ['2160p', '4k', 'uhd']):
        return ('Films', '4K UHD')
    if '1080p' in name:
        return ('Films', '1080p HD')
    if '720p' in name:
        return ('Films', '720p HD')
    if any(k in name for k in ['animation', 'anime', 'pixar', 'disney']):
        return ('Films', 'Films d\'Animation & OAV')
    if any(k in name for k in ['documentaire', 'docu', 'reportage']):
        return ('Films', 'Documentaires & Reportages')

    # Catégorie par défaut
    return ('Films', 'Longs-métrages / Cinéma')

# =============================================================================
# 2. SCANNER MEDIAINFO CLI & GÉNÉRATION DU NFO AUTHENTIQUE T411
# =============================================================================
def get_mediainfo_text(target_path):
    video_file = None
    if target_path.is_file():
        video_file = target_path
    else:
        # Trouver le plus gros fichier vidéo dans le dossier
        candidates = []
        for p in target_path.rglob('*'):
            if p.is_file() and p.suffix.lower() in ['.mkv', '.mp4', '.avi', '.ts', '.m2ts', '.flac', '.mp3']:
                candidates.append((p.stat().st_size, p))
        if candidates:
            candidates.sort(reverse=True)
            video_file = candidates[0][1]

    if not video_file:
        return ""

    try:
        res = subprocess.run(['mediainfo', str(video_file)], capture_output=True, text=True, check=True)
        return res.stdout.strip()
    except Exception:
        return ""

def generate_t411_nfo(release_name, category, sub_category, size_bytes, uploader_name, mediainfo_raw=""):
    def fmt_size(b):
        if b >= 1073741824: return f"{round(b / 1073741824, 2)} Go"
        if b >= 1048576: return f"{round(b / 1048576, 2)} Mo"
        return f"{round(b / 1024, 1)} Ko"

    nfo = f"""=============================================================================
                       T 4 1 1   R É T R O   2 0 2 6
                La Communauté du Partage P2P Francophone
=============================================================================
  RELEASE       : {release_name}
  CATÉGORIE     : {category} ({sub_category})
  TAILLE TOTALE : {fmt_size(size_bytes)} ({size_bytes} octets)
  UPLOADER      : {uploader_name}
  TRACKER       : https://t411.org/announce.php
=============================================================================
                              INFORMATIONS TECHNIQUES
============================================================================="""

    if mediainfo_raw:
        nfo += "\n" + mediainfo_raw + "\n"
    else:
        nfo += f"\n  Format standard conforme BitTorrent T411.\n  Vérifié et certifié conforme par le script d'upload officiel.\n"

    nfo += """=============================================================================
              Le partage est un droit, le ratio un devoir !
              © T411 — https://t411.org/ — Bon seed à tous !
============================================================================="""
    return nfo

# =============================================================================
# 3. CRÉATION DU FICHIER .TORRENT (MKTORRENT OU BENCODE PUR PYTHON)
# =============================================================================
def bencode_str(s):
    if isinstance(s, str): s = s.encode('utf-8')
    return str(len(s)).encode('ascii') + b':' + s

def bencode_int(i):
    return b'i' + str(int(i)).encode('ascii') + b'e'

def bencode_list(l):
    return b'l' + b''.join(bencode_any(x) for x in l) + b'e'

def bencode_dict(d):
    keys = sorted(d.keys(), key=lambda k: k.encode('utf-8') if isinstance(k, str) else k)
    out = b'd'
    for k in keys:
        out += bencode_str(k) + bencode_any(d[k])
    return out + b'e'

def bencode_any(x):
    if isinstance(x, (str, bytes)): return bencode_str(x)
    if isinstance(x, int): return bencode_int(x)
    if isinstance(x, list): return bencode_list(x)
    if isinstance(x, dict): return bencode_dict(x)
    raise ValueError(f"Type non supporté : {type(x)}")

def pick_piece_length(total_size):
    if total_size < 512 * 1024 * 1024:
        return 512 * 1024     # 512 Ko
    if total_size < 2 * 1024 * 1024 * 1024:
        return 1024 * 1024    # 1 Mo
    if total_size < 8 * 1024 * 1024 * 1024:
        return 2048 * 1024    # 2 Mo
    if total_size < 16 * 1024 * 1024 * 1024:
        return 4096 * 1024    # 4 Mo
    return 8192 * 1024        # 8 Mo

def create_torrent_bytes(target_path):
    target_path = Path(target_path).resolve()
    if not target_path.exists():
        raise FileNotFoundError(f"Chemin introuvable : {target_path}")

    # Essayer mktorrent en priorité si disponible (ultra rapide en C)
    mktorrent_out = target_path.parent / (target_path.name + ".temp.torrent")
    try:
        subprocess.run([
            'mktorrent',
            '-a', T411_ANNOUNCE,
            # Mode Hybride Immortel : pas de -p pour laisser la DHT et le PeX actifs
            '-s', 'T411',     # Source tag
            '-o', str(mktorrent_out),
            str(target_path)
        ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if mktorrent_out.exists():
            data = mktorrent_out.read_bytes()
            mktorrent_out.unlink()
            return data
    except Exception:
        pass

    # Générateur pur Python natif si mktorrent absent
    print("⏳ Hachage des pièces en cours (moteur natif)...")
    files_to_hash = []
    if target_path.is_file():
        total_size = target_path.stat().st_size
        files_to_hash.append((target_path, total_size))
    else:
        total_size = 0
        for p in sorted(target_path.rglob('*')):
            if p.is_file():
                sz = p.stat().st_size
                total_size += sz
                files_to_hash.append((p, sz))

    piece_len = pick_piece_length(total_size)
    pieces_hashes = bytearray()
    cur_piece = bytearray()

    for fpath, _ in files_to_hash:
        with open(fpath, 'rb') as fp:
            while True:
                chunk = fp.read(piece_len - len(cur_piece))
                if not chunk:
                    break
                cur_piece.extend(chunk)
                if len(cur_piece) == piece_len:
                    pieces_hashes.extend(hashlib.sha1(cur_piece).digest())
                    cur_piece.clear()

    if len(cur_piece) > 0:
        pieces_hashes.extend(hashlib.sha1(cur_piece).digest())

    info_dict = {
        'name': target_path.name,
        'piece length': piece_len,
        'pieces': bytes(pieces_hashes),
        'source': 'T411'
    }

    if target_path.is_file():
        info_dict['length'] = total_size
    else:
        info_dict['files'] = []
        for fpath, fsize in files_to_hash:
            rel_parts = list(fpath.relative_to(target_path).parts)
            info_dict['files'].append({
                'length': fsize,
                'path': rel_parts
            })

    torrent_dict = {
        'announce': T411_ANNOUNCE,
        'announce-list': [
            [T411_ANNOUNCE],
            ['udp://tracker.opentrackr.org:1337/announce'],
            ['udp://open.stealth.si:80/announce'],
            ['udp://tracker.torrent.eu.org:451/announce']
        ],
        'comment': 'T411 Retro Tracker (https://t411.org)',
        'created by': 'T411 Seedbox Uploader v1.0',
        'creation date': int(os.path.getmtime(target_path)),
        'info': info_dict
    }

    return bencode_dict(torrent_dict)

# =============================================================================
# 4. TÉLÉVERSEMENT VERS L'API T411
# =============================================================================
def upload_to_t411(passkey, release_name, category, sub_category, torrent_bytes, nfo_text, poster_url="", imdb_id=""):
    boundary = "----T411Boundary" + hashlib.md5(os.urandom(16)).hexdigest()
    body = bytearray()

    def add_field(field_name, val):
        body.extend(f"--{boundary}\r\n".encode('ascii'))
        body.extend(f'Content-Disposition: form-data; name="{field_name}"\r\n\r\n'.encode('utf-8'))
        body.extend(str(val).encode('utf-8'))
        body.extend(b"\r\n")

    add_field("passkey", passkey)
    add_field("name", release_name)
    add_field("category", category)
    add_field("sub_category", sub_category)
    add_field("nfo_text", nfo_text)
    if poster_url:
        add_field("poster_url", poster_url)
    if imdb_id:
        add_field("imdb_id", imdb_id)

    # Fichier .torrent
    body.extend(f"--{boundary}\r\n".encode('ascii'))
    body.extend(f'Content-Disposition: form-data; name="torrent_file"; filename="{release_name}.torrent"\r\n'.encode('utf-8'))
    body.extend(b"Content-Type: application/x-bittorrent\r\n\r\n")
    body.extend(torrent_bytes)
    body.extend(b"\r\n")

    body.extend(f"--{boundary}--\r\n".encode('ascii'))

    req = urllib.request.Request(
        T411_API_URL,
        data=bytes(body),
        headers={
            'Content-Type': f'multipart/form-data; boundary={boundary}',
            'User-Agent': 'T411-Seedbox-Uploader/1.0'
        }
    )

    try:
        with urllib.request.urlopen(req, timeout=45) as resp:
            data = resp.read().decode('utf-8')
            return json.loads(data)
    except urllib.error.HTTPError as e:
        err_msg = e.read().decode('utf-8')
        try:
            return json.loads(err_msg)
        except Exception:
            return {'success': False, 'error': f"HTTP {e.code} : {err_msg}"}
    except Exception as e:
        return {'success': False, 'error': str(e)}

# =============================================================================
# 5. INJECTION DANS LE CLIENT BITTORRENT LOCAL (QBITTORRENT / TRANSMISSION)
# =============================================================================
def inject_to_client(client_type, torrent_file_path, save_dir, qbt_host="http://127.0.0.1:8080"):
    print(f"🔄 Injection dans le client BitTorrent ({client_type})...")

    if client_type == 'qbittorrent':
        # Appel API qBittorrent /api/v2/torrents/add
        try:
            bnd = "----QbtBoundary" + hashlib.md5(os.urandom(16)).hexdigest()
            b = bytearray()

            # Paramètre savepath
            b.extend(f"--{bnd}\r\n".encode('ascii'))
            b.extend(b'Content-Disposition: form-data; name="savepath"\r\n\r\n')
            b.extend(str(save_dir).encode('utf-8'))
            b.extend(b"\r\n")

            # Fichier torrent
            b.extend(f"--{bnd}\r\n".encode('ascii'))
            b.extend(f'Content-Disposition: form-data; name="torrents"; filename="{torrent_file_path.name}"\r\n'.encode('utf-8'))
            b.extend(b"Content-Type: application/x-bittorrent\r\n\r\n")
            b.extend(torrent_file_path.read_bytes())
            b.extend(b"\r\n")
            b.extend(f"--{bnd}--\r\n".encode('ascii'))

            req = urllib.request.Request(
                f"{qbt_host}/api/v2/torrents/add",
                data=bytes(b),
                headers={'Content-Type': f'multipart/form-data; boundary={bnd}'}
            )
            with urllib.request.urlopen(req, timeout=10) as r:
                res = r.read().decode('utf-8')
                if 'Ok' in res or r.status == 200:
                    print("✅ Torrent ajouté à qBittorrent ! Le seed démarre.")
                    return True
        except Exception as e:
            print(f"⚠️ Impossible d'ajouter à qBittorrent via WebAPI : {e}")
            print(f"👉 Ouvrez manuellement le fichier généré : {torrent_file_path}")

    elif client_type == 'transmission':
        try:
            subprocess.run([
                'transmission-remote',
                '-a', str(torrent_file_path),
                '-w', str(save_dir)
            ], check=True)
            print("✅ Torrent ajouté à Transmission !")
            return True
        except Exception as e:
            print(f"⚠️ Transmission-remote non accessible : {e}")

    return False

# =============================================================================
# POINT D'ENTRÉE PRINCIPAL
# =============================================================================
def print_categories():
    print("\n📋 Récupération des catégories officielles T411...")
    try:
        req = urllib.request.Request(T411_API_URL, headers={'User-Agent': 'T411-Seedbox-Uploader/1.0'})
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode('utf-8'))
            cats = data.get('categories', {})
            print("=" * 68)
            print("       CATÉGORIES & SOUS-CATÉGORIES OFFICIELLES T411")
            print("=" * 68)
            for key, c in cats.items():
                print(f"\n📂 [{c['name']}] (clé: {key})")
                for s in c.get('subs', []):
                    print(f"   └── {s}")
            print("\n" + "=" * 68)
    except Exception as e:
        print(f"❌ Impossible de charger les catégories : {e}")

def main():
    parser = argparse.ArgumentParser(description="T411 Rétro — Uploader Automatique pour Seedbox")
    parser.add_argument("path", nargs='?', help="Chemin du fichier vidéo/audio/jeu ou dossier à uploader")
    parser.add_argument("--passkey", help="Votre Passkey secrète T411 (disponible dans Mon Compte)")
    parser.add_argument("--categories", action="store_true", help="Afficher l'arborescence complète des catégories et sous-catégories T411")
    parser.add_argument("--name", help="Titre personnalisé de la release (optionnel)")
    parser.add_argument("--category", "--cat", dest="category", help="Catégorie T411 forcée (ex: Films, Séries, Musique, Ebooks, Jeux Vidéo, Applications, Adultes)")
    parser.add_argument("--sub", "--subcat", dest="sub", help="Sous-catégorie forcée (ex: MP3 & Audio, FLAC Lossless, 1080p HD, etc.)")
    parser.add_argument("--imdb", help="Lien ou ID IMDb officiel (ex: tt0172495)")
    parser.add_argument("--poster", help="URL directe de la jaquette/affiche (affiche HD)")
    parser.add_argument("--client", choices=['qbittorrent', 'transmission', 'none'], default='qbittorrent', help="Client BitTorrent local à alimenter")
    parser.add_argument("--qbt-host", default="http://127.0.0.1:8080", help="URL WebUI qBittorrent (par défaut http://127.0.0.1:8080)")

    args = parser.parse_args()

    if args.categories:
        print_categories()
        sys.exit(0)

    if not args.path:
        parser.error("Le chemin 'path' est obligatoire (sauf avec --categories).")
    if not args.passkey:
        parser.error("L'argument --passkey est obligatoire.")
    target_path = Path(args.path).resolve()
    if not target_path.exists():
        print(f"❌ Erreur : Le fichier ou dossier '{target_path}' n'existe pas.")
        sys.exit(1)

    release_name = args.name or target_path.name
    print(f"\n🚀 Démarrage de l'upload T411 pour : {release_name}")

    # 1. Détection ou validation de catégorie
    if args.category:
        cat = normalize_category(args.category)
        sub_cat = args.sub or default_sub_for_category(cat, target_path)
        print(f"📂 Catégorie choisie manuellement : {cat} > {sub_cat}")
    else:
        cat, sub_cat = detect_t411_category(target_path)
        print(f"📂 Catégorie auto-détectée : {cat} > {sub_cat}")
        print(f"💡 Astuce : Vous pouvez forcer la catégorie à tout moment avec l'option --cat (ex: --cat musique)")

    # 2. Scanner MediaInfo
    print("🔍 Analyse MediaInfo en cours...")
    mediainfo_text = get_mediainfo_text(target_path)

    # 3. Création du .torrent local
    print("📦 Création du fichier .torrent conforme T411...")
    torrent_bytes = create_torrent_bytes(target_path)
    total_size = sum(f.stat().st_size for f in target_path.rglob('*') if f.is_file()) if target_path.is_dir() else target_path.stat().st_size

    # 4. Génération NFO
    nfo = generate_t411_nfo(release_name, cat, sub_cat, total_size, "Membre T411", mediainfo_text)

    # 5. Téléversement API T411
    print("📡 Téléversement sur T411 via l'API sécurisée...")
    res = upload_to_t411(args.passkey, release_name, cat, sub_cat, torrent_bytes, nfo, poster_url=args.poster or "", imdb_id=args.imdb or "")

    if not res.get('success'):
        print(f"❌ Erreur lors de l'upload sur T411 : {res.get('error', 'Erreur inconnue')}")
        sys.exit(1)

    print(f"🎉 Succès ! Release enregistrée (ID #{res.get('id')})")
    print(f"🌐 Fiche sur T411 : {res.get('details_url')}")

    # 6. Sauvegarde du .torrent prêt pour le client
    out_torrent_name = res.get('torrent_filename') or f"{release_name}.t411.torrent"
    out_torrent_path = target_path.parent / out_torrent_name

    if res.get('torrent_base64'):
        import base64
        out_torrent_path.write_bytes(base64.b64decode(res['torrent_base64']))
        print(f"💾 Fichier .torrent téléchargé avec votre Passkey : {out_torrent_path}")
    else:
        print(f"📥 Fichier .torrent disponible à l'adresse : {res.get('download_url')}")

    # 7. Injection automatique dans qBittorrent ou Transmission
    if args.client != 'none' and out_torrent_path.exists():
        save_dir = target_path.parent
        inject_to_client(args.client, out_torrent_path, save_dir, args.qbt_host)

    print("\n⚡ Vous commencez à toucher +2 Mo d'Upload offert par heure dès la première annonce !")
    print("✨ Bon seed sur T411 Rétro !\n")

if __name__ == "__main__":
    main()
