# -*- coding: utf-8 -*-
"""The global quality applied to lists of TMDb titles (Pro tebe rows, the detail's recommendations, TMDb rows, search).
No network: the services a title runs on come from the cache (wcs/services/store.lookup); a title whose services are
not known yet is judged by its own data, and fetching them is left to the rows that show it.
"""
from wcs.quality import rules, settings


def _media(item, media):
    kind = item.get('media_type') or media
    return 'movie' if kind == 'movie' else 'tv'


def classes(items, media=None):
    """{(media, id): service class} of the TMDb items whose services the cache knows."""
    from wcs.services import catalog, store
    pairs = [(_media(i, media), i['id']) for i in items if i.get('id')]
    if not pairs:
        return {}
    found, _missing = store.lookup(pairs)
    return {store.parse_key(k): catalog.class_of(v) for k, v in found.items()}


def judged(items, media=None, values=None):
    """[(item, worth offering)] of TMDb items (dicts with an id; media_type or `media`), in their order."""
    values = values or settings.values()
    known = classes(items, media)
    return [(item, rules.judge(item, values, known.get((_media(item, media), item.get('id'))) or 0))
            for item in items]


def keep(items, media=None, values=None):
    """Only the items worth offering (the rows that suggest)."""
    return [item for item, good in judged(items, media, values) if good]


def search_order(items, media=None, values=None):
    """Every item, the ones worth offering first (search: the user asked for it, so nothing is hidden). Items that are
    not titles (people) keep their place among the good ones."""
    titles = [(i, n) for n, i in enumerate(items) if (i.get('media_type') or media) in ('movie', 'tv')]
    verdict = {n: good for (_i, n), (_item, good) in zip(titles, judged([i for i, _n in titles], media, values))}
    return [item for _key, item in sorted(enumerate(items), key=lambda pair: (not verdict.get(pair[0], True), pair[0]))]
