"""Tiny client for the torrent search API (standard library only, Python 3.8+).

    from trb_client import Client
    c = Client("https://therarbg.com", api_key=None)   # key optional: 60/min + 50,000/day instead of 30/min + 10,000/day
    for t in c.search(q="dune part two", sort="quality", clean=1, limit=5)["results"]:
        print(t["qualityScore"], t["name"], t["magnet"])
    best = c.title("tt1375666")["torrents"][0]

Every method returns the decoded JSON. Errors raise ApiError (status, body);
on HTTP 429 the client waits for Retry-After once and retries.
Guide: <site>/developers/   Spec: <site>/api/openapi.json
"""
import json
import time
import urllib.error
import urllib.parse
import urllib.request

__all__ = ['Client', 'ApiError']


class ApiError(Exception):
    def __init__(self, status, body):
        super().__init__(f'HTTP {status}: {body[:200]}')
        self.status, self.body = status, body


class Client:
    def __init__(self, base_url='https://therarbg.com', api_key=None, timeout=20, user_agent='trb-client/1.0'):
        self.base = base_url.rstrip('/')
        self.api_key, self.timeout, self.ua = api_key, timeout, user_agent

    def _get(self, path, params=None, _retry=True):
        q = {k: v for k, v in (params or {}).items() if v is not None and v != ''}
        url = self.base + path + ('?' + urllib.parse.urlencode(q, doseq=True) if q else '')
        req = urllib.request.Request(url, headers={'User-Agent': self.ua, 'Accept': 'application/json'})
        if self.api_key:
            req.add_header('X-Api-Key', self.api_key)
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as r:
                return json.loads(r.read().decode('utf-8'))
        except urllib.error.HTTPError as e:
            body = e.read().decode('utf-8', 'replace')
            if e.code == 429 and _retry:
                time.sleep(min(60, int(e.headers.get('Retry-After') or 5)))
                return self._get(path, params, _retry=False)
            raise ApiError(e.code, body) from None

    def search(self, **filters):
        """q, category, imdb, season, episode, resolution, source, codec, hdr, audio, language,
        year_min, year_max, rating_min, genre, min_seeders, size_min_gb, size_max_gb, no_cam,
        sort (seeders|date|size|quality|relevance), page, limit, clean"""
        return self._get('/api/v1/search/', filters)

    def title(self, imdb, season=None, episode=None):
        return self._get(f'/api/v1/title/{imdb}/', {'season': season, 'episode': episode})

    def extras(self, imdb, country=None):
        return self._get(f'/api/v1/title/{imdb}/extras/', {'country': country})

    def suggest(self, q):
        return self._get('/api/v1/suggest/', {'q': q})

    def calendar(self, imdb_ids=()):
        return self._get('/api/v1/calendar/', {'imdb': ','.join(imdb_ids)})

    def upcoming(self, type='movie', country=None):
        return self._get('/upcoming/', {'format': 'json', 'type': type, 'country': country})

    def collection(self, tmdb_collection_id):
        return self._get(f'/collections/{tmdb_collection_id}/', {'format': 'json'})

    def streaming(self, service='netflix', country=None, type='movie'):
        return self._get(f'/streaming/{service}/', {'format': 'json', 'country': country, 'type': type})

    def status(self):
        return self._get('/api/v1/status/')

    def best(self, imdb, resolution=None):
        """The best torrent of a title (highest quality score, then seeders), optionally of one resolution."""
        for t in self.title(imdb)['torrents']:
            if resolution is None or t.get('resolution') == resolution:
                return t
        return None
