# -*- coding: utf-8 -*-
"""The one quality judgement of TMDb titles in the whole addon and skin (docs/plan/genre-browser/070, 900 kolo 7).
Pure: no Kodi, no network.

No title is judged by its votes alone: a famous film may run nowhere (Nedotknutelní) and a Czech one has no TMDb
votes (Okresní přebor 7); a big CZ service or a rental store vouches for a title. The thresholds (`values`) come from
the global setting Kvalita návrhů (wcs/quality/settings.py), a genre page may override them for itself.

Two sides of the same rules: `queries` asks TMDb discover for exactly the titles of an origin (the genre listing,
merged by date in wcs/genres/cursor.py) and `keep` tests what discover cannot; `judge` decides any other title
(Pro tebe, the detail's rows, TMDb rows, the order of search results). Measured 2026-10-29
(docs/plan/genre-browser/060, data/tmdb-probe.json).
"""
from wcs.services import catalog as services

ORIGINS = ('western', 'world', 'anime', 'asia')
DEFAULT = 'western'
WESTERN = ('en', 'fr', 'de', 'es', 'it', 'pl', 'sv', 'da', 'no', 'nl', 'fi', 'pt', 'hu', 'is')
HOME = ('cs', 'sk')
# "Nezápadní" for TMDb (it has no "every language but"): the languages with titles of >= 50 votes (060 §T4)
NON_WESTERN = ('ja', 'ko', 'zh', 'cn', 'ru', 'hi', 'ta', 'te', 'th', 'tr', 'id', 'fa', 'ar', 'ml', 'bn', 'kn', 'tl',
               'vi', 'uk', 'he', 'ms', 'mr', 'pa', 'ur', 'el', 'ro', 'bg', 'sr', 'hr', 'et', 'lt', 'lv', 'ka', 'kk')
ASIA = ('ja', 'ko', 'zh', 'cn', 'th')
ANIME_KEYWORD = 210024
ANIMATION = 16                # TMDb genre Animovaný
KNOWN_VOTES = 100            # this many votes: known, whatever its rating (a 5.5 blockbuster stays)
NON_WESTERN_RATING = 6.5     # a non-western title without a service needs a convincing weighted rating too
# The prior of the weighted rating: a title with few votes is pulled towards it (a 9.0 from 2 votes is ~6.6).
PRIOR_RATING, PRIOR_VOTES = 5.5, 8

NO_VOTES = {'west_votes': 0, 'nw_svc_votes': 0, 'nw_votes': 0, 'rating': 0.0}   # the rules without thresholds
SUBSCRIBED = '|'.join(services.SUBSCRIPTION)
ANYHOW = '|'.join(services.SUBSCRIPTION + services.STORE)


def _langs(codes):
    return '|'.join(codes)


def _ids(ids):
    return '|'.join(str(i) for i in ids)


def queries(origin, values):
    """[(rule name, extra discover params)] of an origin; `values` the thresholds (wcs/quality/settings.values).
    Every rule adds `watch_region` only when it filters by a service."""
    west_votes, svc_votes, nw_votes = int(values['west_votes']), int(values['nw_svc_votes']), int(values['nw_votes'])
    big = {'watch_region': services.REGION, 'with_watch_providers': _ids(services.BIG),
           'with_watch_monetization_types': SUBSCRIBED}
    big_or_rent = {'watch_region': services.REGION, 'with_watch_providers': _ids(services.BIG + services.RENT),
                   'with_watch_monetization_types': ANYHOW}
    rent = {'watch_region': services.REGION, 'with_watch_providers': _ids(services.RENT),
            'with_watch_monetization_types': '|'.join(services.STORE)}
    no_anime = {'without_keywords': ANIME_KEYWORD}
    if origin == 'world':
        return [('svc', dict(big, with_original_language=_langs(WESTERN + HOME))),
                ('home', {'with_original_language': _langs(HOME)}),
                ('rent', dict(rent, with_original_language=_langs(WESTERN), **{'vote_count.gte': west_votes})),
                ('votes', {'vote_count.gte': west_votes}),
                ('nw_svc', dict(big_or_rent, with_original_language=_langs(NON_WESTERN), **{'vote_count.gte': svc_votes}))]
    if origin == 'anime':
        return [('votes', {'with_keywords': ANIME_KEYWORD, 'vote_count.gte': west_votes}),
                ('any_svc', dict(big_or_rent, with_keywords=ANIME_KEYWORD))]
    if origin == 'asia':           # live action: TMDb misses the anime keyword on some (Detective Conan), so no animation
        live = dict(no_anime, without_genres=ANIMATION)
        return [('votes', {**live, 'with_original_language': _langs(ASIA), 'vote_count.gte': west_votes}),
                ('any_svc', {**big_or_rent, **live, 'with_original_language': _langs(ASIA)})]
    return [('svc', dict(big, with_original_language=_langs(WESTERN + HOME))),               # rules 1-2
            ('home', {'with_original_language': _langs(HOME)}),                               # rule 5
            ('rent', dict(rent, with_original_language=_langs(WESTERN), **{'vote_count.gte': west_votes})),   # rule 3
            ('votes', {'with_original_language': _langs(WESTERN), 'vote_count.gte': west_votes}),             # rule 4
            ('nw_svc', {**big_or_rent, **no_anime, 'with_original_language': _langs(NON_WESTERN),
                        'vote_count.gte': svc_votes}),                                        # rule 6
            ('nw', {**no_anime, 'with_original_language': _langs(NON_WESTERN), 'vote_count.gte': nw_votes})]  # rule 7


def bayes(rating, votes, prior_rating=PRIOR_RATING, prior_votes=PRIOR_VOTES):
    votes = max(0, int(votes or 0))
    return (votes * float(rating or 0) + prior_votes * prior_rating) / (votes + prior_votes)


def keep(rule, item, values, known=False):
    """True when `item` (a TMDb list item, its texts already fixed by wcs/metadata/texts.py) found by `rule` belongs
    in the listing. What TMDb filtered (language, service, votes) is not asked again; this tests what it cannot.
    Every title needs a poster and an overview: the hero is never empty (Standa 2026-10-29)."""
    if known:
        return True
    if not item.get('poster_path') or not item.get('overview'):
        return False
    if rule in ('svc', 'home', 'rent', 'nw_svc', 'any_svc'):
        return True
    votes = int(item.get('vote_count') or 0)
    weighted = bayes(item.get('vote_average'), votes)
    if rule == 'nw':
        return weighted >= NON_WESTERN_RATING
    return weighted >= float(values['rating']) or votes >= KNOWN_VOTES


def _get(item, *names):
    """The first field a TMDb list item / detail or a Pro tebe card (wcs/foryou/features.card) has."""
    for name in names:
        if item.get(name) not in (None, ''):
            return item[name]
    return None


def _genres(item):
    found = _get(item, 'genre_ids', 'genres') or []
    return {g['id'] if isinstance(g, dict) else int(g) for g in found if g}


def is_anime(item):
    """Anime: TMDb's keyword when the item brings keywords, else a Japanese animation."""
    block = item.get('keywords')
    if isinstance(block, dict):
        words = block.get('keywords') or block.get('results') or []
        if any(k.get('id') == ANIME_KEYWORD for k in words):
            return True
    return ANIMATION in _genres(item) and _get(item, 'original_language', 'language') == 'ja'


def judge(item, values, service=services.NONE, origin=None):
    """True when a TMDb title is worth offering: the same rules as the genre listing's queries, decided on the title
    itself. `service`: its class of CZ services (wcs/services/catalog.class_of; unknown = NONE, never a reason to
    drop it); `origin`: the filter Původ (the global setting's when None). A title without a poster never is."""
    origin = origin or values.get('origin') or DEFAULT
    if not _get(item, 'poster_path', 'poster'):
        return False
    lang = _get(item, 'original_language', 'language') or ''
    votes = int(_get(item, 'vote_count', 'votes') or 0)
    weighted = bayes(_get(item, 'vote_average', 'rating'), votes)
    well = weighted >= float(values['rating']) or votes >= KNOWN_VOTES
    big, rent = service == services.BIG_CLASS, service == services.RENT_CLASS
    anime = is_anime(item)
    if origin == 'anime':
        return anime and (votes >= int(values['west_votes']) or big or rent)
    if origin == 'asia':
        return (lang in ASIA and ANIMATION not in _genres(item)
                and (votes >= int(values['west_votes']) or big or rent))
    if lang in HOME:
        return True
    if lang in WESTERN:
        return big or (votes >= int(values['west_votes']) and (well or rent))
    if anime and origin != 'world':
        return False                                  # anime has its own filter
    if (big or rent) and votes >= int(values['nw_svc_votes']):
        return True
    if origin == 'world':
        return votes >= int(values['west_votes']) and well
    return votes >= int(values['nw_votes']) and weighted >= NON_WESTERN_RATING


def junk(item):
    """What the test of the defaults counts as junk: nobody voted, nobody looks at it, often no poster."""
    return not item.get('votes') and float(item.get('popularity') or 0) < 1.0


def weighted(item, prior_rating=6.0, prior_votes=200):
    """The rating of the "best" rows (Nejlépe hodnocené, Nejlepší z desetiletí): a strong prior, so a 8.4 from 30 votes
    does not beat a 8.2 from 20 000."""
    return bayes(item.get('rating'), item.get('votes'), prior_rating, prior_votes)


def gem(item, rating=7.0, votes=(30, 1500)):
    """A hidden gem: rated well, known by few (between the two vote counts)."""
    count = int(item.get('votes') or 0)
    return votes[0] <= count <= votes[1] and bayes(item.get('rating'), count, 6.0, 30) >= rating


def star(item, threshold=7.5, min_votes=10):
    """The rating badge on a listing card: only for a convincing high rating (the listing stays sorted by date)."""
    count = int(item.get('votes') or 0)
    return count >= min_votes and bayes(item.get('rating'), count) >= threshold
