# -*- coding: utf-8 -*-
"""TMDb as the source of the genre browser (docs/plan/genre-browser/010, 050 §Požadavek na G1).

The UI only knows this interface (genres, listing queries, rows, countries), so a ČSFD source or a merged one can come
later without touching it. Every answer goes through the http cache of library.db (wcs/foryou/api.py), with the
lifetimes of the addon settings; tests replace `api.FETCH`.
"""
from datetime import date, timedelta

from wcs.foryou import api
from wcs.genres import catalog, cursor
from wcs.quality import rules as quality
from wcs.metadata import texts

NAME = 'tmdb'
DAY, HOUR = 86400, 3600
# The default lifetimes; the addon settings (genre_ttl_*) replace them (settings.ttl()).
TTL = {'genres': 7 * DAY, 'list': 24 * HOUR, 'countries': 30 * DAY}
# Countries of the Země filter after "Vše": the home countries, then the most producing ones by discover counts (films
# + series, measured 2026-10-27, docs/plan/genre-browser/900-decisions.md). "Další…" lists all 251.
HOME_COUNTRIES = ('CZ', 'SK')
# Before 1993 TMDb files Czech and Slovak titles under Czechoslovakia (XC: 297 films with >= 10 votes, CZ itself 322):
# Česko and Slovensko include it, or Kulový blesk and Pelíšky's elders would be missing.
COUNTRY_QUERY = {'CZ': 'CZ|XC', 'SK': 'SK|XC'}
TOP_COUNTRIES = ('US', 'GB', 'FR', 'JP', 'IT', 'CA', 'IN', 'DE', 'ES', 'KR', 'MX', 'CN', 'HK', 'BR', 'RU', 'AU', 'TR', 'SU',
                 'SE', 'PL')
OLDEST_YEAR = 1874                       # the oldest film on TMDb (Passage de Vénus); the year list ends there
RECENT_DAYS = 90                         # Populární teď: titles of the last ~90 days
SERVICE_DAYS = 180                       # Teď na službách v ČR: films released in the last ~half year


class Source(object):
    name = NAME

    def __init__(self, ttl=None, today=None):
        self.ttl = dict(TTL, **(ttl or {}))
        self.today = today or date.today()

    # ------------------------------------------------------------------ genres and countries
    def genre_lists(self, cached_only=False):
        """{'movie': [{'id', 'name'}], 'tv': [...]} of TMDb (cs-CZ); {} for a media TMDb did not answer."""
        out = {}
        for media in ('movie', 'tv'):
            path = 'genre/{}/list'.format(media)
            data = _cached(path, {}, self.ttl['genres']) if cached_only else api.get(path, None, self.ttl['genres'])
            out[media] = (data or {}).get('genres') or []
        return out

    def extras(self, cached_only=True):
        return catalog.extras(self.genre_lists(cached_only))

    def countries(self):
        """[(iso, name)] of all countries TMDb knows, by their Czech name ([] offline)."""
        rows = _countries(self.ttl['countries'])
        named = [(r['iso_3166_1'], r.get('native_name') or r.get('english_name') or r['iso_3166_1'])
                 for r in rows if isinstance(r, dict) and r.get('iso_3166_1')]
        return sorted(named, key=lambda pair: pair[1].lower())

    # ------------------------------------------------------------------ listing
    def queries(self, key, filters, extra=None, values=None):
        """{query name: discover params} of the listing of genre `key` with `filters` ({'media': ''|movie|tv,
        'year': ''|'1985', 'country': ''|'CZ', 'sort': date|rating|popularity, 'origin': western|world|anime|asia}):
        one query per media and rule of the origin ('movie/svc', …; wcs/quality/rules.queries), or one per media
        ('movie') without an origin or `values`."""
        out = {}
        for media in catalog.media_of(key, filters.get('media', ''), extra):
            base = self.base(media, catalog.ids(key, media, extra), filters)
            if not filters.get('origin') or values is None:
                out[media] = base
                continue
            for rule, params in quality.queries(filters['origin'], values):
                query = dict(base, **params)
                query['vote_count.gte'] = max(int(base.get('vote_count.gte') or 0), int(params.get('vote_count.gte') or 0))
                if not query['vote_count.gte']:
                    del query['vote_count.gte']
                out['{}/{}'.format(media, rule)] = query
        return out

    def base(self, media, genre_ids, filters, since=None, until=None):
        field = cursor.DATE_FIELD[media]
        params = {'with_genres': '|'.join(str(g) for g in genre_ids), 'include_adult': 'false',
                  field + '.lte': self.today.isoformat()}
        if media == 'tv':
            params['include_null_first_air_dates'] = 'false'
        year = str(filters.get('year') or '')
        if year.isdigit():
            params[field + '.gte'] = '{}-01-01'.format(year)
            params[field + '.lte'] = min('{}-12-31'.format(year), self.today.isoformat())
        if since:
            params[field + '.gte'] = max(since, params.get(field + '.gte', since))
        if until:
            params[field + '.lte'] = min(until, params[field + '.lte'])
        if filters.get('country'):
            params['with_origin_country'] = COUNTRY_QUERY.get(filters['country'], filters['country'])
        votes = int(filters.get('rating_votes') or 100) if filters.get('sort') == 'rating' else 0
        if votes:
            params['vote_count.gte'] = votes
        return params

    def fetch(self, media, params):
        """One discover page (list) or None (offline, no key, error), with readable titles and filled overviews
        (wcs/metadata/texts.py: the same page in English when the Czech one lacks them, cached the same way)."""
        path = 'discover/{}'.format(media)
        data = api.get(path, params, self.ttl['list'])
        if data is None:
            return None
        found = [r for r in data.get('results') or [] if isinstance(r, dict) and r.get('id')]
        if not texts.needs_english(found):
            return found
        english = api.get(path, dict(params, language=api.ENGLISH), self.ttl['list']) or {}
        return texts.fix(found, english.get('results') or [])

    def total(self, media, params):
        """total_results of a discover query (the harness, the year list)."""
        data = api.get('discover/{}'.format(media), dict(params, page=1), self.ttl['list'])
        return int((data or {}).get('total_results') or 0)

    # ------------------------------------------------------------------ the other rows of the genre page
    def row_queries(self, row, key, filters, extra=None, decade=None):
        """[(media, params)] of a side row; its titles are ranked by the caller (wcs/genres/rows.py)."""
        calls = []
        for media in catalog.media_of(key, filters.get('media', ''), extra):
            ids = catalog.ids(key, media, extra)
            plain = {k: v for k, v in filters.items() if k in ('country', 'year')}
            if row == 'gn_popular':
                since = (self.today - timedelta(days=RECENT_DAYS)).isoformat()
                params = self.base(media, ids, {'country': plain.get('country')}, since=since)
                calls += [(media, dict(params, sort_by='popularity.desc', page=p)) for p in (1, 2)]
            elif row == 'gn_top':
                params = self.base(media, ids, plain)
                calls += [(media, dict(params, sort_by='vote_average.desc', page=p,
                                       **{'vote_count.gte': 1000 if media == 'movie' else 300})) for p in (1, 2)]
                calls.append((media, dict(params, sort_by='vote_count.desc', page=1)))
            elif row == 'gn_gems':
                params = self.base(media, ids, plain)
                calls += [(media, dict(params, sort_by='vote_average.desc', page=p,
                                       **{'vote_count.gte': 40, 'vote_count.lte': 1500 if media == 'movie' else 600}))
                          for p in (1, 2, 3)]
            elif row == 'gn_decade':
                first, last = decade
                params = self.base(media, ids, {'country': plain.get('country')}, since='{}-01-01'.format(first),
                                   until='{}-12-31'.format(last))
                calls += [(media, dict(params, sort_by='vote_count.desc', page=p)) for p in (1, 2)]
            elif row == 'gn_services':
                since = (self.today - timedelta(days=SERVICE_DAYS)).isoformat()
                params = self.base(media, ids, {'country': plain.get('country')}, since=since)
                params.update(dict(quality.queries('western', quality.NO_VOTES))['svc'])       # western on a big service
                calls += [(media, dict(params, sort_by='popularity.desc', page=p)) for p in (1, 2)]
            elif row == 'gn_foryou':
                params = self.base(media, ids, plain)
                calls += [(media, dict(params, sort_by='popularity.desc', page=p)) for p in (1, 2)]
                calls += [(media, dict(params, sort_by='vote_count.desc', page=p)) for p in (1, 2)]
        return calls


def _countries(ttl):
    """configuration/countries answers a list, which api.get does not take: cached here as {'results': [...]}."""
    from wcs.metadata import TMDbCache
    params = {'language': api.LANGUAGE}
    cached = TMDbCache.get_from_cache('configuration/countries', params, ttl)
    if cached is not None:
        return cached.get('results') or []
    try:
        data = (api.FETCH or api._http)('configuration/countries', params)
    except Exception as exc:
        import xbmc
        xbmc.log('[Milionář Žánry] countries failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
        return []
    rows = data if isinstance(data, list) else (data or {}).get('results') or []
    if rows:
        TMDbCache.set_to_cache('configuration/countries', params, {'results': rows})
    return rows


def _cached(path, params, ttl):
    """The cached answer only (the Pro tebe row never calls the network)."""
    from wcs.metadata import TMDbCache
    query = dict(params)
    query.setdefault('language', api.LANGUAGE)
    return TMDbCache.get_from_cache(path, query, ttl)
