# -*- coding: utf-8 -*-
"""The side rows of the genre page (docs/plan/genre-browser/010 §Další řádky). Pure: the TMDb answers come in, ranked
cards go out; no Kodi, no network.

Doporučeno pro tebe, Teď na službách v ČR, Populární teď, Nejlépe hodnocené, Skryté klenoty, Nejlepší z desetiletí.
A side row never repeats a title of a side row above it (like Pro tebe); the listing (Výpis) is complete and shares
with nobody. A title a big CZ service streams ranks higher in every row, one a rental store has a little
(docs/plan/genre-browser/070 §Scoring; `classes` from the services cache, wcs/services).
"""
from wcs.foryou import features as F
from wcs.genres import contract
from wcs.quality import rules as quality
from wcs.services import catalog as services

SERVICE_BONUS = {services.BIG_CLASS: 1.25, services.RENT_CLASS: 1.1}

ROW_SIZE = 20


def cards(answers):
    """[(media, results)] -> unique cards in the order they came."""
    out, seen = [], set()
    for media, results in answers:
        for data in results or []:
            key = F.key(media, data['id'])
            if key in seen or data.get('adult'):
                continue
            seen.add(key)
            out.append(F.card(data, media))
    return out


def _affinity(card, taste):
    """0..1: how much the household likes the card's genres ({folded genre id: 0..1} of the Pro tebe profile)."""
    values = [taste.get(g, 0.0) for g in F.folded_genres(card['genres'])]
    return max(values) if values else 0.0


def bonus(card, classes):
    """The service factor of a card: {'movie:603': class} of the cached services (wcs/services/catalog.class_of)."""
    return SERVICE_BONUS.get((classes or {}).get(F.key(card['media'], card['id'])), 1.0)


def rank(row, answers, taste=None, snapshot=None, exclude=(), classes=None):
    """The ranked cards of side row `row` from its TMDb answers [(media, results)]."""
    taste = taste or {}
    pool = [c for c in cards(answers) if F.key(c['media'], c['id']) not in exclude and c['poster']]
    if row == contract.POPULAR:
        pool.sort(key=lambda c: -c['popularity'] * bonus(c, classes))
    elif row == contract.TOP or row.startswith('gn_decade_'):
        pool = [c for c in pool if c['votes'] >= 50]
        pool.sort(key=lambda c: -quality.weighted(c) * bonus(c, classes))
    elif row == contract.GEMS:
        pool = [c for c in pool if quality.gem(c)]
        pool.sort(key=lambda c: -(quality.bayes(c['rating'], c['votes'], 6.0, 30) * (1.0 + 0.15 * _affinity(c, taste))
                                  * bonus(c, classes)))
    elif row == contract.SERVICES:
        # every title streams on a big service (the query): the household's taste and the rating order them
        pool.sort(key=lambda c: -(quality.weighted(c, 6.0, 50) / 10.0 + 0.3 * _affinity(c, taste)))
    elif row == contract.FORYOU:
        pool = foryou(pool, taste, snapshot, classes)
    return pool


def foryou(pool, taste, snapshot=None, classes=None):
    """Doporučeno pro tebe in one genre: the Pro tebe titles of the genre first (their own score), then the genre's
    well-known titles by quality and the household's genre taste. Webshare decides afterwards (wcs/genres/page.py)."""
    scored = {}
    items = (snapshot or {}).get('items') or {}
    for card in pool:
        key = F.key(card['media'], card['id'])
        known = items.get(key)
        if known:
            value = 2.0 + float(known.get('score') or 0)
        else:
            value = quality.weighted(card, 6.4, 150) / 10.0 + 0.3 * _affinity(card, taste)
            if card['votes'] < 50:
                value *= 0.7
        scored[key] = value * bonus(card, classes)
    return sorted(pool, key=lambda c: -scored[F.key(c['media'], c['id'])])


def snapshot_cards(snapshot, genre_ids, medias, filters):
    """Pro tebe titles of the genre for Doporučeno pro tebe (Typ and Rok apply; a country is unknown for a film)."""
    if filters.get('country'):
        return []
    wanted = set(genre_ids)
    out = []
    for item in ((snapshot or {}).get('items') or {}).values():
        if item.get('media') not in medias or not wanted & set(F.folded_genres(item.get('genres') or [])):
            continue
        if filters.get('year') and str(item.get('year')) != str(filters['year']):
            continue
        out.append(item)
    return sorted(out, key=lambda i: -float(i.get('score') or 0))


def taste_of(snapshot_sources, weights=None):
    """{folded genre id: 0..1} from the snapshot's genre sources (catalog.genre_sources), weighted like the genre row."""
    total = {}
    weights = weights or {}
    for source, values in (snapshot_sources or {}).items():
        sign = -1 if source == 'dislike' else 1
        for gid, value in values.items():
            total[int(gid)] = total.get(int(gid), 0.0) + sign * float(weights.get(source, 1.0)) * float(value)
    best = max(list(total.values()) + [0.0])
    return {g: max(0.0, v / best) for g, v in total.items()} if best > 0 else {}
