# -*- coding: utf-8 -*-
"""The questionnaire of the guide (docs/plan/onboarding/000-plan.md D9-D13, D34, D35): the genres of the genre section,
then the best known films and series of the chosen genres, each genre in turn, as the global Kvalita návrhů sees them
(wcs/quality: western titles, services and ratings first, like Pro tebe and Žánry), each with the CZ services it runs on.

Data only, never a window: the wizard asks, a thread of `Prefetch` fetches ahead (TMDb answers go through the cache of
wcs/foryou/api, the services through wcs/services/store). What the household chose goes into the library as liked titles
in Moje filmy / Moje seriály, the seeds of Pro tebe (`save`).
"""
import threading

from wcs.foryou import api, features as F
from wcs.genres import catalog
from wcs.quality import lists as quality_lists, rules

FIRST = 20                               # the cards a step shows first (D11), then Načíst další
PAGE = 20                                # what Načíst další adds
MIN_VOTES = {'movie': 300, 'tv': 150}    # known titles: the household should recognise what it is asked about
# the most voted first: the films and series most people have seen, not this week's releases
MAX_PAGES = 12
POSTER = 'https://image.tmdb.org/t/p/w342'
BACKDROP = 'https://image.tmdb.org/t/p/w1280'
LANGS = '|'.join(rules.WESTERN + rules.HOME)


def genres():
    """[(key, name)] of the genre section, in its order (D12)."""
    from wcs.genres.widgets import genre_name
    return [(key, genre_name(key)) for key in catalog.listed('')]


# A genre TMDb has no series of asks for the series of the nearest series genre (D35).
TV_NEAREST = {'horror': (9648, 80), 'thriller': (9648, 80), 'romance': (18,), 'history': (10768,), 'music': (18,),
              'tvmovie': (18,)}


def genre_ids(key, media):
    """The TMDb genre ids the questionnaire asks for `key` in `media` (D35)."""
    ids = tuple(catalog.ids(key, media))
    if not ids and media == 'tv':
        ids = TV_NEAREST.get(key, ())
    return tuple(sorted(ids))


def streams_of(media, keys):
    """The genre id groups of the chosen genres, one per distinct group, the genre section's order first (D34)."""
    order = [k for k in catalog.POPULARITY if k in keys] + sorted(k for k in keys if k not in catalog.POPULARITY)
    out = []
    for key in order:
        ids = genre_ids(key, media)
        if ids and ids not in out:
            out.append(ids)
    return out


def params(media, ids, page):
    """The discover query of one page of one genre: the most voted known titles."""
    return {'sort_by': 'vote_count.desc', 'with_genres': '|'.join(str(i) for i in ids), 'page': page,
            'vote_count.gte': MIN_VOTES[media], 'with_original_language': LANGS, 'include_adult': 'false'}


class Stream(object):
    """The good titles of one genre, page after page of TMDb's discover."""

    def __init__(self, media, ids):
        self.media, self.ids = media, ids
        self.page, self.done, self.queue = 0, False, []

    def _page(self):
        self.page += 1
        items = api.results('discover/{}'.format(self.media), params(self.media, self.ids, self.page))
        if not items or self.page >= MAX_PAGES:
            self.done = True
        self.queue.extend(F.card(item, self.media) for item in quality_lists.keep(items, self.media)
                          if item.get('poster_path'))

    def take(self, seen):
        """The next card nobody has shown yet, or None when the genre has no more."""
        while True:
            while self.queue:
                card = self.queue.pop(0)
                key = F.key(self.media, card['id'])
                if key not in seen:
                    seen.add(key)
                    return card
            if self.done:
                return None
            self._page()


class Pool(object):
    """The good titles of one media for the chosen genres: the best known title of each genre in turn (D34)."""

    def __init__(self, media, keys):
        self.media, self.keys = media, tuple(keys)
        self.cards, self.turn = [], 0
        self.seen = set()
        self.lock = threading.Lock()
        self.streams = [Stream(media, ids) for ids in streams_of(media, self.keys)]

    @property
    def done(self):
        return all(stream.done and not stream.queue for stream in self.streams)

    def fill(self, count):
        """At least `count` cards (fewer when TMDb has no more); returns all cards so far."""
        with self.lock:
            while len(self.cards) < count and not self.done:
                stream = self.streams[self.turn % len(self.streams)]
                self.turn += 1
                card = stream.take(self.seen)
                if card is not None:
                    self.cards.append(card)
            return list(self.cards)

    def services(self, cards):
        """{'movie:603': services} of these cards, fetched now when the cache does not know them."""
        from wcs.services import store
        return store.ensure([(c['media'], c['id']) for c in cards])


class Prefetch(object):
    """Fetches the next step's cards while the household is still choosing (D13): the films and series of the genres
    chosen so far, a thread that only fetches."""

    def __init__(self):
        self.pools = {}
        self.thread = None
        self.wanted = None

    def pool(self, media, keys):
        key = (media, tuple(sorted(keys)))
        if key not in self.pools:
            self.pools[key] = Pool(media, key[1])
        return self.pools[key]

    def start(self, keys):
        """The genres changed: fetch the first cards of both media in the background."""
        self.wanted = tuple(sorted(keys))
        if not self.wanted:
            return
        wanted = self.wanted

        def work():
            for media in ('movie', 'tv'):
                if self.wanted != wanted:
                    return
                pool = self.pool(media, wanted)
                pool.services(pool.fill(FIRST)[:FIRST])

        self.thread = threading.Thread(target=work, name='milionar-onboarding-prefetch', daemon=True)
        self.thread.start()

    def ready(self, media, keys):
        pool = self.pools.get((media, tuple(sorted(keys))))
        return pool is not None and (pool.done or len(pool.cards) >= FIRST)


def facts(card):
    """The line under the hero's title: year, rating, genres."""
    parts = [str(card['year'])] if card.get('year') else []
    if card.get('rating'):
        parts.append('★ {:.1f}'.format(card['rating']).replace('.', ','))
    return '  ·  '.join(parts)


def save(movies, series):
    """The chosen titles into Moje filmy / Moje seriály as liked (D9): the seeds of Pro tebe. Returns how many."""
    from wcs.library2 import store
    count = 0
    for media, cards in (('movie', movies), ('tv', series)):
        for card in cards:
            store.set_in_list(media, card['id'], True)
            store.set_feedback(media, card['id'], 'like')
            count += 1
    return count
