#!/usr/bin/env python3
import requests
import os

QBT_URL = "http://localhost:8080"
QBT_USER = "admin"
QBT_PASS = "Vocalize_Void_Rage_Visor_Ladies_Undercook_Spokesman_Fraternal"
DOWNLOAD_DIR = "/mnt/downloads/torrent/completed/"   # <--- Update me!

session = requests.Session()

def login():
    r = session.post(f"{QBT_URL}/api/v2/auth/login", data={"username": QBT_USER, "password": QBT_PASS})
    assert r.text == "Ok.", "Login failed"

def get_all_torrents():
    r = session.get(f"{QBT_URL}/api/v2/torrents/info")
    r.raise_for_status()
    return r.json()

def get_torrent_files(hash_):
    r = session.get(f"{QBT_URL}/api/v2/torrents/files", params={"hash": hash_})
    r.raise_for_status()
    return r.json()

def main():
    login()
    referenced_files = set()
    torrents = get_all_torrents()
    for torrent in torrents:
        hash_ = torrent["hash"]
        save_path = torrent["save_path"]
        files = get_torrent_files(hash_)
        for f in files:
            referenced_files.add(os.path.abspath(os.path.join(save_path, f["name"])))

    # List all real files (recursive)
    actual_files = set()
    for root, dirs, files in os.walk(DOWNLOAD_DIR):
        for f in files:
            actual_files.add(os.path.abspath(os.path.join(root, f)))

    orphaned = sorted(actual_files - referenced_files)

    print(f"Orphaned files (not referenced by any torrent):")
    for f in orphaned:
        print(f)

if __name__ == "__main__":
    main()