# -*- coding: utf-8 -*-
"""The genres of the browser (docs/plan/genre-browser/010 §Žánry). Pure: no Kodi, no network.

A genre of the browser is not a TMDb id: films and series have their own genre lists. Every entry says which TMDb ids it
asks for each media (OR), so the genre page can switch between Filmy / Seriály / Oboje on the same genre:

  * Filmy  -> the 19 film genres,
  * Seriály -> the 16 series genres (the combined ones as they are: "Akční a dobrodružný"),
  * Vše / Oboje -> the film genres with the series genres folded in (TV "Sci-Fi & Fantasy" -> Sci-Fi and Fantasy), like
    wcs/foryou/features.folded_genres, plus the TV-only genres.

TV-only genres (Kids, News, Reality, Soap, Talk) are hidden unless the widget says otherwise. Names are our own strings
(cs/sk/en, TMDb does not translate the series genres); a genre TMDb adds later keeps TMDb's name.
"""

# key -> (string id, film genre ids, series genre ids)
GENRES = {
    'action': (35501, (28,), (10759,)),
    'adventure': (35502, (12,), (10759,)),
    'animation': (35503, (16,), (16,)),
    'comedy': (35504, (35,), (35,)),
    'crime': (35505, (80,), (80,)),
    'documentary': (35506, (99,), (99,)),
    'drama': (35507, (18,), (18,)),
    'family': (35508, (10751,), (10751,)),
    'fantasy': (35509, (14,), (10765,)),
    'history': (35510, (36,), ()),
    'horror': (35511, (27,), ()),
    'music': (35512, (10402,), ()),
    'mystery': (35513, (9648,), (9648,)),
    'romance': (35514, (10749,), ()),
    'scifi': (35515, (878,), (10765,)),
    'tvmovie': (35516, (10770,), ()),
    'thriller': (35517, (53,), ()),
    'war': (35518, (10752,), (10768,)),
    'western': (35519, (37,), (37,)),
    'action_adventure': (35520, (28, 12), (10759,)),
    'scifi_fantasy': (35521, (878, 14), (10765,)),
    'war_politics': (35522, (10752,), (10768,)),
    'kids': (35523, (), (10762,)),
    'news': (35524, (), (10763,)),
    'reality': (35525, (), (10764,)),
    'soap': (35526, (), (10766,)),
    'talk': (35527, (), (10767,)),
}
TV_ONLY = ('kids', 'news', 'reality', 'soap', 'talk')
# the genres of each mode ('' = Vše: films with the series folded in)
MOVIE = ('action', 'adventure', 'animation', 'comedy', 'crime', 'documentary', 'drama', 'family', 'fantasy', 'history',
         'horror', 'music', 'mystery', 'romance', 'scifi', 'tvmovie', 'thriller', 'war', 'western')
TV = ('action_adventure', 'animation', 'comedy', 'crime', 'documentary', 'drama', 'family', 'kids', 'mystery', 'news',
      'reality', 'scifi_fantasy', 'soap', 'talk', 'war_politics', 'western')
ALL = MOVIE + TV_ONLY
# The fixed order after "my" genres: titles with >= 100 votes per genre, films + series, measured 2026-10-27
# (scripts/genre_harness, docs/plan/genre-browser/900-decisions.md).
POPULARITY = ('drama', 'comedy', 'thriller', 'action', 'crime', 'romance', 'horror', 'animation', 'adventure', 'mystery',
              'family', 'scifi', 'fantasy', 'scifi_fantasy', 'action_adventure', 'history', 'documentary', 'war', 'music',
              'tvmovie', 'western', 'kids', 'soap', 'war_politics', 'reality', 'talk', 'news')
# A TMDb genre the table does not know yet: its own entry 'tmdb<id>' with TMDb's name.
EXTRA = 'tmdb'


def mode_keys(mode):
    return MOVIE if mode == 'movie' else TV if mode == 'tv' else ALL


def ids(key, media, extra=None):
    """TMDb genre ids of `key` for `media` (empty: the genre has no titles of that media)."""
    if key in GENRES:
        return GENRES[key][1 if media == 'movie' else 2]
    entry = (extra or {}).get(key)
    return tuple(entry['ids'].get(media) or ()) if entry else ()


def media_of(key, wanted, extra=None):
    """The media the genre page asks for: `wanted` is 'movie', 'tv' or '' (both); a genre without titles of a media
    drops it ('' -> only the other one)."""
    medias = ('movie', 'tv') if wanted not in ('movie', 'tv') else (wanted,)
    return tuple(m for m in medias if ids(key, m, extra))


def extras(api_lists):
    """Genres TMDb has that the table does not: {'tmdb<id>': {'name', 'ids': {media: (id,)}}}.
    `api_lists`: {'movie': [{'id', 'name'}], 'tv': [...]} (genre/<media>/list)."""
    known = {media: {i for entry in GENRES.values() for i in entry[1 if media == 'movie' else 2]} for media in ('movie', 'tv')}
    found = {}
    for media in ('movie', 'tv'):
        for genre in (api_lists or {}).get(media) or []:
            gid = genre.get('id')
            if not gid or int(gid) in known[media]:
                continue
            entry = found.setdefault(EXTRA + str(gid), {'name': genre.get('name') or str(gid), 'ids': {}})
            entry['ids'][media] = (int(gid),)
    return found


def listed(mode, show_tv_only=False, extra=None):
    """The genre keys of a mode in the fixed order (popularity, then the TMDb extras)."""
    keys = [k for k in POPULARITY if k in mode_keys(mode) and (show_tv_only or k not in TV_ONLY)]
    for key, entry in sorted((extra or {}).items()):
        if mode in ('movie', 'tv') and not entry['ids'].get(mode):
            continue
        keys.append(key)
    return keys


def taste_ids(key):
    """The folded (film) genre ids a genre stands for in the Pro tebe profile (wcs/foryou/features.folded_genres):
    its film ids (Fantasy is 14, not the 878 its series genre folds onto too), else its folded series ids (Kids)."""
    from wcs.foryou.features import folded_genres
    if key not in GENRES:
        return ()
    _string, movie, tv = GENRES[key]
    return tuple(movie) or tuple(folded_genres(tv))


# Scoring (docs/plan/genre-browser/010 §Scoring): the profile's genre weights per source, folded onto film genre ids.
SOURCES = ('library', 'watched', 'like', 'dislike')
SEED_SOURCE = {'list': 'library', 'watched': 'watched', 'started': 'watched', 'tried': 'watched', 'like': 'like',
               'pick': 'like', 'genre': 'like', 'dislike': 'dislike'}   # genre: chosen in the guide (onboarding D36)


def genre_sources(seeds):
    """{source: {genre id: weight}} from the Pro tebe seeds [(kind, weight, folded genre ids)]; a seed counts for each
    of its genres by its weight, split over them (a drama-comedy is half of each), dislikes count negative."""
    out = {source: {} for source in SOURCES}
    for kind, weight, genres in seeds:
        source = SEED_SOURCE.get(kind)
        if not source or not genres:
            continue
        share = abs(float(weight)) / len(genres)
        for gid in genres:
            out[source][int(gid)] = out[source].get(int(gid), 0.0) + share
    return {source: {g: round(v, 4) for g, v in values.items()} for source, values in out.items()}


def scores(keys, sources, weights):
    """{key: score 0..1} of the genres: Σ weight(source) × the genre's share in that source, relative to the best.
    A dislike lowers the score (weights['dislike'] is applied as a minus)."""
    raw = {}
    for key in keys:
        total = 0.0
        for source in SOURCES:
            values = (sources or {}).get(source) or {}
            value = max([values.get(g, values.get(str(g), 0.0)) for g in taste_ids(key)] or [0.0])
            total += (-1 if source == 'dislike' else 1) * float(weights.get(source, 1.0)) * value
        raw[key] = total
    best = max(list(raw.values()) + [0.0])
    return {key: (value / best if best > 0 else 0.0) for key, value in raw.items()}


def ordered(keys, sources, weights, threshold, first=()):
    """'My' genres (score >= threshold) by score, then the others in their given order. The genres chosen in the guide
    (`first`, onboarding D36) lead, by score among themselves. Returns (keys, mine)."""
    found = scores(keys, sources, weights)
    rank = lambda k: (-found[k], keys.index(k))
    chosen = sorted([k for k in keys if k in first], key=rank)
    mine = chosen + sorted([k for k in keys if k not in chosen and found[k] > 0 and found[k] >= threshold], key=rank)
    return mine + [k for k in keys if k not in mine], mine
