"""
Platform Gateway — qBittorrent integration (download status).
"""

import json
import urllib.request
import urllib.parse

from config import QBITTORRENT_HOST, QBITTORRENT_PORT, QBITTORRENT_USERNAME, QBITTORRENT_PASSWORD


def handle_downloads_status(handler):
    """Get active downloads from qBittorrent."""
    base = f"http://{QBITTORRENT_HOST}:{QBITTORRENT_PORT}"
    try:
        # Login
        login_data = urllib.parse.urlencode({"username": QBITTORRENT_USERNAME, "password": QBITTORRENT_PASSWORD}).encode()
        req = urllib.request.Request(f"{base}/api/v2/auth/login", data=login_data)
        with urllib.request.urlopen(req, timeout=5) as resp:
            cookie = resp.headers.get("Set-Cookie", "").split(";")[0]

        # Get torrents
        req2 = urllib.request.Request(f"{base}/api/v2/torrents/info?filter=all&sort=added_on&reverse=true&limit=20",
                                      headers={"Cookie": cookie})
        with urllib.request.urlopen(req2, timeout=5) as resp2:
            torrents_raw = json.loads(resp2.read())

        torrents = []
        for t in torrents_raw:
            torrents.append({
                "hash": t["hash"],
                "name": t["name"],
                "progress": round(t["progress"] * 100, 1),
                "state": t["state"],
                "size": t["total_size"],
                "downloaded": t["downloaded"],
                "dlSpeed": t["dlspeed"],
                "upSpeed": t["upspeed"],
                "eta": t.get("eta", 0),
                "addedOn": t.get("added_on", 0),
                "category": t.get("category", ""),
            })
        handler._send_json({"torrents": torrents, "total": len(torrents)})
    except Exception as e:
        handler._send_json({"torrents": [], "total": 0, "error": str(e)})
