# -*- coding: utf-8 -*-
"""The CZ services and their classes (docs/plan/genre-browser/070 §Pojmy). Pure: no Kodi, no network.

A title's services are stored compactly (wcs/services/store.py): {'flatrate'|'ads'|'free'|'rent'|'buy': [[id, logo, name]]}.
The class of a title decides its scoring and the filter "Původ": a big subscription service (Netflix … Lepší TV) means
a known title you can watch now, a rental store (Apple TV Store, Amazon Video, Rakuten) a released one, a small service
nothing (10 256 films with 0 votes sit on some service: measured 2026-10-29, data/tmdb-probe.json).
"""

REGION = 'CZ'
# Netflix, HBO Max, Disney+, Prime Video, Apple TV, SkyShowtime, Oneplay, Prima Plus, Canal+, Lepší TV (070 §Pojmy)
BIG = (8, 1899, 337, 119, 350, 1773, 2536, 1928, 381, 1939)
RENT = (2, 10, 35)                          # Apple TV Store, Amazon Video, Rakuten
SUBSCRIPTION = ('flatrate', 'ads', 'free')  # what a big service counts by
STORE = ('rent', 'buy')
KINDS = SUBSCRIPTION + STORE
LOGO_BASE = 'https://image.tmdb.org/t/p/w154'
BADGES = 2                                  # logos on a poster; the rest is "+N"

NONE, SMALL, RENT_CLASS, BIG_CLASS = 0, 1, 2, 3


def compact(region_block):
    """The stored form of TMDb's `results.CZ` block (None or {} = runs nowhere: stored as {})."""
    out = {}
    for kind in KINDS:
        rows = []
        for provider in (region_block or {}).get(kind) or []:
            if isinstance(provider, dict) and provider.get('provider_id'):
                rows.append([int(provider['provider_id']), provider.get('logo_path') or '',
                             provider.get('provider_name') or ''])
        if rows:
            out[kind] = rows
    return out


def class_of(services):
    """BIG_CLASS when a big service streams it, RENT_CLASS when a rental store has it, SMALL for any other service,
    NONE for nothing (or not known yet: None)."""
    if not services:
        return NONE
    subscribed = {row[0] for kind in SUBSCRIPTION for row in services.get(kind) or []}
    if subscribed & set(BIG):
        return BIG_CLASS
    stored = {row[0] for kind in STORE for row in services.get(kind) or []}
    if stored & set(RENT):
        return RENT_CLASS
    return SMALL if subscribed or stored else NONE


def _rank(provider_id):
    if provider_id in BIG:
        return BIG.index(provider_id)
    if provider_id in RENT:
        return len(BIG) + RENT.index(provider_id)
    return len(BIG) + len(RENT) + 1


def providers(services):
    """[(id, logo, name, kinds)] of a title, each provider once: the big services first (in BIG's order), the rental
    stores, then the rest; subscription before store within the same service."""
    found = {}
    for kind in KINDS:
        for provider_id, logo, name in (services or {}).get(kind) or []:
            entry = found.setdefault(provider_id, [provider_id, logo, name, []])
            entry[3].append(kind)
            entry[1] = entry[1] or logo
    return [tuple(entry) for entry in sorted(found.values(), key=lambda e: (_rank(e[0]), e[2].lower()))]


def badges(services):
    """(logo urls of the poster badge (at most BADGES), '+N' or '') of a title."""
    listed = [p for p in providers(services) if p[1]]
    logos = [LOGO_BASE + p[1] for p in listed[:BADGES]]
    rest = len(listed) - len(logos)
    return logos, ('+{}'.format(rest) if rest > 0 else '')


def summary(services, labels):
    """'Předplatné: Netflix, HBO Max · Půjčovna: Apple TV Store' of the detail; `labels` {group: text} for the groups
    'subscription', 'rent', 'buy'."""
    groups = (('subscription', SUBSCRIPTION), ('rent', ('rent',)), ('buy', ('buy',)))
    parts = []
    for group, kinds in groups:
        names = []
        for provider_id, _logo, name, provider_kinds in providers(services):
            if set(provider_kinds) & set(kinds) and name not in names:
                names.append(name)
        if names:
            parts.append('{}: {}'.format(labels[group], ', '.join(names)))
    return ' · '.join(parts)
