# -*- coding: utf-8 -*-
"""The window of the first-run guide (resources/skins/Default/1080i/onboarding/DialogMilionarOnboarding.xml).

Vítej (account or not, D29) -> Účet (QR, only with the account) -> TMDb (required, D4) -> Webshare (may be skipped,
D6) -> ChatGPT (what it does, connected on the web, D39) -> Žánry -> Filmy -> Seriály (D9-D11) -> Home on Pro tebe with its first row ready
(D14). Key steps already satisfied are skipped (D30); which steps the user walks is wcs/onboarding/plan.py. The same
window is the single key window of the settings (`single`, D17).

Kodi's GUI is not thread-safe: everything that touches the window runs in its own thread (onInit, onClick, onAction);
the threads of wcs.onboarding.picks and the first Pro tebe build only fetch and compute. Whatever the user waits for
says what it waits for (the status line with a spinner, and Kodi's progress, D13).
"""
import threading
import time

import xbmc
import xbmcaddon
import xbmcgui

from wcs.onboarding import picks, plan, state
from wcs.onboarding.account_step import AccountStep

ADDON_ID = 'plugin.video.milionar'
XML = 'onboarding/DialogMilionarOnboarding.xml'
B1, B2, B3, BUTTONS = 11, 12, 13, 9000
AI_LIST, GENRES, TITLES = 530, 510, 520
BACK = (xbmcgui.ACTION_NAV_BACK, xbmcgui.ACTION_PREVIOUS_MENU)
TMDB_CHECK = 'https://api.themoviedb.org/3/configuration'
KEY_LENGTH = 32
SETTLE_S = 1.5                           # a pause in picking the series before the first Pro tebe is built again

S_PREPARING, S_SETUP_FAILED, S_PROGRESS = 35807, 35808, 35809
S = dict(welcome=(35820, 35821, 35822), account=(36002, 36003, 36049), tmdb=(35824, 35829, 35830), webshare=(35838, 35839, 35840),
         ai=(35850, 35851, 35852), chatgpt=(36073, 36074, 36075), genres=(35856, 35857, 35858), movies=(35874, 35860, 35861),
         series=(35875, 35862, 35863))
S_ENTER_KEY, S_CHECKING, S_KEY_OK, S_KEY_BAD, S_KEY_OFFLINE, S_KEY_SHORT, S_CONTINUE = (
    35831, 35832, 35833, 35834, 35835, 35836, 35837)
S_LOGIN, S_SKIP, S_LOGGING_IN, S_LOGGED_IN, S_LOGIN_BAD, S_LOGIN_OFFLINE, S_LOGGED_OUT, S_LOGIN_HINT, S_OTHER = (
    35841, 35842, 35843, 35844, 35845, 35846, 35847, 35848, 35849)
S_AI_SAVED, S_AI_HINT, S_AI_BAD = 35853, 35854, 35855
S_CONTINUE_N, S_LOADING_MOVIES, S_LOADING_SERIES, S_MORE, S_MORE_TEXT, S_BUILDING = 35859, 35864, 35865, 35866, 35867, 35868
S_LEAVE_HEAD, S_LEAVE_TEXT, S_RESTORE, S_TIP, S_HINT_GENRES, S_HINT_TITLES, S_FINISH_N, S_NOTHING = (
    35869, 35870, 35872, 35828, 35876, 35873, 35877, 35878)
S_WITH_ACCOUNT, S_WITHOUT_ACCOUNT, S_SIGNED_AS, S_WELCOME_SIGNED, S_WELCOME_NO_KEY = 36051, 36005, 36010, 36050, 36053


def _log(message, level=xbmc.LOGINFO):
    xbmc.log('[Milionář Onboarding] ' + message, level)


def check_tmdb_key(key):
    """'ok', 'bad' (TMDb does not know it) or 'offline' (no answer: never accepted unchecked, D7 of the plan)."""
    import requests
    try:
        response = requests.get(TMDB_CHECK, params={'api_key': key}, timeout=10)
    except Exception:
        return 'offline'
    if response.status_code in (401, 404):
        return 'bad'
    return 'ok' if response.ok else 'offline'


class Guide(AccountStep, xbmcgui.WindowXMLDialog):

    def __init__(self, *args, **kwargs):
        self.single = kwargs.pop('single', '')
        super(Guide, self).__init__(*args, **kwargs)
        self.taste = self.single == 'taste'               # the questionnaire alone (the first card of Pro tebe)
        if self.taste:
            self.single = ''
        self.init_account()
        self.account_path = False                        # the user chose the account on Vítej (D29)
        self.visited = set()
        self.skipped = self.satisfied()
        self.step = 'genres' if self.taste else self.single or state.step(self.addon)
        if not self.single and not self.taste and (self.step in self.skipped or self.step == 'ai'):   # D39
            self.step = plan.following(self.path(), self.step) or 'welcome'
        self.chosen_genres = {key for key in self.addon.getSetting('onboarding_genres').split(',') if key}   # D16
        self.chosen = {'movie': {}, 'tv': {}}            # media -> {id: card}
        self.prefetch = picks.Prefetch()
        self.build = None                                # the first Pro tebe build (a thread)
        self.wanted = self.built = None                  # the answers it builds from, the answers of the stored one
        self.changed = 0.0
        self.finished = False
        self.ready = False
        self.cards, self.shown = {}, 0

    @property
    def addon(self):
        """A fresh Addon each time: every xbmcaddon.Addon holds its own copy of the settings and a write saves the whole
        copy (Kodi's Addon.cpp, Omega), so a copy held across the guide would undo what the service wrote meanwhile
        (the account's sync, its keys)."""
        return xbmcaddon.Addon(ADDON_ID)

    # ------------------------------------------------------------------ texts and layout

    def text(self, string_id, *args):
        value = self.addon.getLocalizedString(string_id)
        return value.format(*args) if args else value

    def status(self, message='', kind=''):
        self.setProperty('ob.status', message)
        self.setProperty('ob.status.kind', kind)

    def buttons(self, first='', second='', third='', first_off=False):
        self.setProperty('ob.b1', first)
        self.setProperty('ob.b2', second)
        self.setProperty('ob.b3', third)
        self.setProperty('ob.b1.off', '1' if first_off else '')

    def below(self, target):
        """Down from the buttons goes to the step's cards (the XML's conditional <ondown>)."""

    def show(self, step):
        self.step = step
        self.visited.add(step)
        if not self.single and not self.taste and not state.finished():
            state.remember(self.addon, step)             # D16; a finished guide (only a key missing) stays finished
        kicker, title, text = S[step]
        index, count = plan.progress(self.path(), step)
        self.setProperty('ob.index', str(index))
        self.setProperty('ob.count', str(count))
        self.setProperty('ob.progress', self.text(S_PROGRESS, index, count))
        self.setProperty('ob.kicker', self.text(kicker).upper())
        self.setProperty('ob.title', self.text(title))
        titles = step in ('movies', 'series')               # the focused title stands where the text would
        self.setProperty('ob.text', '' if titles else self.text(text))
        self.setProperty('ob.hint', self.text(text) if titles else '')
        self.status()
        self.setProperty('ob.step', step)
        getattr(self, 'show_' + step)()
        if step in ('tmdb', 'webshare', 'ai') and self.signed_in() and not self.getProperty('ob.status'):
            from wcs.account import client
            self.status(self.text(36030, client.server() + 'settings/accounts'))   # S12: or add it on the web

    def focus(self, control):
        """The control may become visible only with the next frame (its step property was just set): focus it once it
        shows, so Kodi never refuses ("Control 11 in window 13000 has been asked to focus, but it can't")."""
        for attempt in range(20):
            try:
                shows = self.getControl(control).isVisible()      # this window's control (Control.cpp, Omega)
            except RuntimeError:
                shows = False
            if not shows and attempt < 19:                       # the last try focuses whatever it finds
                xbmc.sleep(30)
                continue
            try:
                self.setFocusId(control)
            except RuntimeError:
                pass
            if self.getFocusId() == control or (control == B1 and self.getFocusId() in (B1, B2, B3)):
                return
            xbmc.sleep(30)

    # ------------------------------------------------------------------ the steps

    def path(self):
        """The steps of this run; signed in, the account step is behind the user and no longer counts. The questionnaire
        alone (the first card of Pro tebe) is just its three steps."""
        if self.taste:
            return list(plan.TASTE)
        return plan.path(self.account_path and not self.signed_in(), self.skipped, state.finished())

    def satisfied(self):
        """The key steps there is nothing to do in (D30), except those the user has seen in this guide."""
        from wcs import user_data
        addon = xbmcaddon.Addon(ADDON_ID)
        have = {'tmdb': state.has_key(addon), 'webshare': user_data.webshare_ready(addon)}
        return {step for step, ok in have.items() if ok} - self.visited

    def show_welcome(self):
        if self.signed_in():                             # the guide of an account (D28): no account choice
            name = self.addon.getSetting('account_name')
            self.setProperty('ob.text', self.text(S_WELCOME_NO_KEY if state.finished() else S_WELCOME_SIGNED, name))
            self.status(self.text(S_SIGNED_AS, name), 'ok')
            self.buttons(self.text(S_CONTINUE))
        else:
            self.buttons(self.text(S_WITH_ACCOUNT), self.text(S_WITHOUT_ACCOUNT))
        self.focus(B1)

    def show_tmdb(self):
        self.setProperty('ob.tip', self.text(S_TIP))
        if state.has_key(self.addon):
            self.status(self.text(S_KEY_OK), 'ok')
            self.buttons(self.text(S_CONTINUE), self.text(S_ENTER_KEY))
        else:
            self.buttons(self.text(S_ENTER_KEY))
        self.focus(B1)

    def show_webshare(self):
        user = self.addon.getSetting('wsuser')
        self.setProperty('ob.account.on', '1' if user and self.addon.getSetting('wspass') else '')
        if user and self.addon.getSetting('wspass'):
            self.setProperty('ob.account', user)
            self.setProperty('ob.account.text', self.addon.getSetting('webshare_vip_info'))
            self.buttons(self.text(S_CONTINUE), self.text(S_OTHER))
        else:
            self.setProperty('ob.account', self.text(S_LOGGED_OUT))
            self.setProperty('ob.account.text', self.text(S_LOGIN_HINT))
            self.buttons(self.text(S_LOGIN), self.text(S_SKIP))
        self.focus(B1)

    def show_ai(self):
        from wcs.ai import accounts
        items = []
        for provider, (name, _client) in accounts.PROVIDERS.items():
            saved = accounts.has_key(provider, self.addon)
            item = xbmcgui.ListItem(name, self.text(S_AI_SAVED) if saved else '')
            item.setArt({'icon': 'DefaultAddonProgram.png'})
            item.setProperty('ob.on', '1' if saved else '')
            item.setProperty('ob.provider', provider)
            items.append(item)
        control = self.getControl(AI_LIST)
        control.reset()
        control.addItems(items)
        any_key = any(accounts.has_key(p, self.addon) for p in accounts.PROVIDERS)
        self.buttons(self.text(S_CONTINUE if any_key else S_SKIP))
        self.setProperty('ob.hint', self.text(S_AI_HINT))
        self.below(AI_LIST)
        self.focus(AI_LIST)

    def show_chatgpt(self):
        """D39: what Milionář in ChatGPT does (the cards with examples in the XML); connecting it is on the web."""
        from wcs.account import client
        self.setProperty('ob.hint', self.text(36076, client.server() + 'settings/chatgpt'))
        self.buttons(self.text(S_CONTINUE))
        self.focus(B1)

    def show_genres(self):
        control = self.getControl(GENRES)
        control.reset()
        items = []
        for key, name in picks.genres():
            item = xbmcgui.ListItem(name)
            item.setArt({'icon': 'DefaultGenre.png'})
            item.setProperty('ob.key', key)
            item.setProperty('ob.on', '1' if key in self.chosen_genres else '')
            items.append(item)
        control.addItems(items)
        self.update_genres()
        self.setProperty('ob.hint', self.text(S_HINT_GENRES))
        self.below(GENRES)
        self.focus(GENRES)

    def update_genres(self):
        count = len(self.chosen_genres)
        self.buttons(self.text(S_CONTINUE_N, count), first_off=not count)

    def show_movies(self):
        self.show_titles('movie')

    def show_series(self):
        self.show_titles('tv')

    def media(self):
        return 'movie' if self.step == 'movies' else 'tv'

    def show_titles(self, media):
        control = self.getControl(TITLES)
        control.reset()
        self.shown = 0
        self.update_titles()
        self.below(TITLES)
        pool = self.prefetch.pool(media, self.chosen_genres)
        if not self.prefetch.ready(media, self.chosen_genres):
            self.status(self.text(S_LOADING_MOVIES if media == 'movie' else S_LOADING_SERIES), 'busy')
        progress = None
        if not self.prefetch.ready(media, self.chosen_genres):
            progress = xbmcgui.DialogProgressBG()
            progress.create('Milionář', self.text(S_LOADING_MOVIES if media == 'movie' else S_LOADING_SERIES))
        try:
            cards = pool.fill(picks.FIRST)
            services = pool.services(cards)
        finally:
            if progress is not None:
                progress.close()
        self.status()
        if not cards:
            self.status(self.text(S_NOTHING), 'error')
            self.focus(B1)
            return
        self.add_cards(control, cards, services, pool)
        self.focus(TITLES)

    def add_cards(self, control, cards, services, pool):
        from wcs.services import store
        shown = self.shown if control.size() else 0
        if control.size() and control.getListItem(control.size() - 1).getProperty('ob.more'):
            control.removeItem(control.size() - 1)
        items = []
        for card in cards[shown:]:
            item = xbmcgui.ListItem(card['title'])
            item.setArt({'poster': picks.POSTER + card['poster'] if card['poster'] else '',
                         'fanart': picks.BACKDROP + card['backdrop'] if card['backdrop'] else ''})
            tag = item.getVideoInfoTag()
            tag.setTitle(card['title'])
            tag.setPlot(card['overview'])
            item.setProperty('ob.id', str(card['id']))
            item.setProperty('ob.facts', picks.facts(card))
            if card.get('rating'):
                item.setProperty('ob.rating', '{:.1f}'.format(card['rating']).replace('.', ','))
            item.setProperty('ob.on', '1' if card['id'] in self.chosen[card['media']] else '')
            store.apply(item, services.get(store.key(card['media'], card['id'])) or {})
            items.append(item)
        control.addItems(items)
        self.shown = len(cards)
        self.cards.update((c['id'], c) for c in cards)
        if not pool.done:
            more = xbmcgui.ListItem(self.text(S_MORE), self.text(S_MORE_TEXT))
            more.setProperty('ob.more', '1')
            control.addItem(more)

    def update_titles(self):
        count = len(self.chosen[self.media()])
        label = S_FINISH_N if self.step == 'series' else S_CONTINUE_N
        self.buttons(self.text(label, count))

    # ------------------------------------------------------------------ Kodi events

    def onInit(self):
        from wcs.skin import appearance
        appearance.publish()
        if self.ready:                                   # back from Kodi's keyboard or a dialog: nothing to redo
            return
        self.ready = True
        self.setProperty('ob.single', self.single or ('1' if self.taste else ''))   # no step progress
        self.show(self.step)

    def onClick(self, control):
        handler = getattr(self, 'click_' + self.step, None)
        if handler:
            handler(control)

    def onAction(self, action):
        if action.getId() in BACK:
            self.back()

    def back(self):
        if self.single or (self.taste and self.step == 'genres'):
            self.close()
            return
        if self.step == 'account':
            self.back_account()
            return
        previous = plan.previous(self.path(), self.step)
        if previous is None:
            self.leave()                                 # Vítej (D31)
        else:
            self.show(previous)

    def leave(self):
        """D5, D31: the guide is mandatory. Go on with it, or Kodi's own look comes back (clean Estuary)."""
        # yesnocustom tells Zpět (-1) from the button (0); no custom label = no third button (GUIDialogYesNo.cpp, Omega)
        choice = xbmcgui.Dialog().yesnocustom(self.text(S_LEAVE_HEAD), self.text(S_LEAVE_TEXT), '',
                                              nolabel=self.text(S_RESTORE), yeslabel=self.text(S_CONTINUE),
                                              defaultbutton=xbmcgui.DLG_YESNO_YES_BTN)
        if choice != 0:                                  # Pokračovat, or Zpět out of the dialog: the guide goes on
            self.focus(B1)
            return
        self.close()
        restore_kodi_look()

    # Vítej
    def click_welcome(self, control):
        if self.signed_in():
            if control == B1:
                self.next_step()
        elif control == B1:
            self.account_path = True                     # D29: the account first
            self.show('account')
        elif control == B2:
            self.without_account()

    def without_account(self):
        """Pokračovat bez účtu: the classic path, from TMDb on (D29)."""
        self.account_path = False
        self.step = 'welcome'
        self.next_step()

    # Účet Milionář (docs/plan/milionar-account/040 §1-2, S2, S11, S12, S30): wcs/onboarding/account_step.py
    def signed_in_continue(self):
        """Signed in on the account step: the account's keys skip their steps (S12); a finished account goes Home (S11),
        an account whose guide is open goes on where it stands (D28)."""
        self.skipped = self.satisfied()
        self.chosen_genres = {key for key in self.addon.getSetting('onboarding_genres').split(',') if key}
        if state.finished() and state.has_key():
            self.finish_from_account()
            return
        stored = state.step()
        steps = self.path()
        self.show(stored if stored in plan.TASTE and stored in steps else plan.following(steps, 'account'))

    def signed_in(self):
        from wcs.account import state as account_state
        account_state.invalidate()
        return account_state.signed_in()

    def save_to_account(self, kind, body):
        """S12: a key entered here goes into the account (the server checks it) and comes back as the account's."""
        from wcs.account import client, sync
        try:
            client.request('PUT', 'sync/secrets/' + kind, body, timeout=30)
            sync.fetch_secrets()
            return 'ok'
        except client.AccountError as exc:
            return 'bad' if exc.code == 'invalid_key' or exc.status in (400, 401, 422) else 'offline'

    def finish_from_account(self):
        """The guide is finished (the account's, S11, or on this device with only a key missing, D33): Pro tebe and the
        first row ready, then Home (as finish())."""
        self.status(self.text(S_BUILDING), 'busy')
        self.buttons()
        progress = xbmcgui.DialogProgressBG()
        progress.create(self.text(S_BUILDING), self.text(S_BUILDING))
        try:
            from wcs.foryou import service as foryou_service
            foryou_service.build_now('account')
            progress.update(85)
            settle_snapshot()
            state.remember(self.addon, state.DONE)
            prepare_rows()
            progress.update(100)
        finally:
            progress.close()
        state.remember(self.addon, state.DONE)
        self.finished = True
        self.close()

    # TMDb
    def click_tmdb(self, control):
        if control == B1 and state.has_key(self.addon) and self.getProperty('ob.status.kind') == 'ok':
            self.next_step()
        elif control in (B1, B2):
            self.enter_tmdb_key()

    def enter_tmdb_key(self):
        keyboard = xbmc.Keyboard('', self.text(S_ENTER_KEY))
        keyboard.doModal()
        if not keyboard.isConfirmed():
            return
        key = keyboard.getText().strip().replace(' ', '')
        if not key:
            return
        if len(key) != KEY_LENGTH:
            self.status(self.text(S_KEY_SHORT), 'error')
            return
        self.status(self.text(S_CHECKING), 'busy')
        result = check_tmdb_key(key)
        if result == 'ok' and self.signed_in():
            result = self.save_to_account('tmdb', {'value': key})
        if result != 'ok':
            self.status(self.text(S_KEY_BAD if result == 'bad' else S_KEY_OFFLINE), 'error')
            return
        self.addon.setSetting('tmdb_api_key', key)
        self.addon.setSetting('tmdb_status', 'Přihlášen k TMDb')
        self.status(self.text(S_KEY_OK), 'ok')
        self.buttons(self.text(S_CONTINUE), self.text(S_ENTER_KEY))
        self.focus(B1)
        if not self.single:
            xbmc.sleep(700)                              # the check mark is seen, then the next step
            self.next_step()

    # Webshare
    def click_webshare(self, control):
        signed_in = bool(self.addon.getSetting('wsuser') and self.addon.getSetting('wspass'))
        if control == B1 and signed_in:
            self.next_step()
        elif (control == B1 and not signed_in) or (control == B2 and signed_in):
            self.webshare_login()
        elif control == B2:
            self.next_step()

    def webshare_login(self):
        from wcs.webshare import WebshareClient
        keyboard = xbmc.Keyboard(self.addon.getSetting('wsuser'), self.text(35880))
        keyboard.doModal()
        if not keyboard.isConfirmed() or not keyboard.getText().strip():
            return
        user = keyboard.getText().strip()
        keyboard = xbmc.Keyboard('', self.text(35881), True)
        keyboard.doModal()
        if not keyboard.isConfirmed() or not keyboard.getText():
            return
        password = keyboard.getText()
        self.status(self.text(S_LOGGING_IN), 'busy')
        if self.signed_in():
            result = self.save_to_account('webshare', {'username': user, 'password': password})
            if result != 'ok':
                self.status(self.text(S_LOGIN_BAD if result == 'bad' else S_LOGIN_OFFLINE), 'error')
                return
            self.show_webshare()
            self.status(self.text(S_LOGGED_IN), 'ok')
            if not self.single:
                xbmc.sleep(900)
                self.next_step()
            return
        try:
            token = WebshareClient.login(user, password, self.addon, lambda *a, **k: None, open_settings_on_fail=False)
        except Exception as exc:
            _log('webshare login failed: {}'.format(type(exc).__name__), xbmc.LOGWARNING)
            self.status(self.text(S_LOGIN_OFFLINE), 'error')
            return
        if not token:
            self.status(self.text(S_LOGIN_BAD), 'error')
            return
        self.addon.setSetting('wsuser', user)
        self.addon.setSetting('wspass', password)
        self.addon.setSetting('webshare_status', 'Přihlášen jako: {}'.format(user))
        self.addon.setSetting('token', token)
        try:
            WebshareClient.refresh_vip_info(self.addon, token_override=token, log_context='onboarding')
        except Exception as exc:
            _log('webshare vip info failed: {}'.format(type(exc).__name__), xbmc.LOGWARNING)
        self.show_webshare()
        self.status(self.text(S_LOGGED_IN), 'ok')
        if self.single:
            return
        xbmc.sleep(900)
        self.next_step()

    # ChatGPT (D39)
    def click_chatgpt(self, control):
        if control == B1:
            self.next_step()

    # AI
    def click_ai(self, control):
        if control == AI_LIST:
            item = self.getControl(AI_LIST).getSelectedItem()
            if item is not None:
                self.ai_key(item.getProperty('ob.provider'), item.getLabel())
        elif control == B1:
            self.next_step()

    def ai_key(self, provider, name):
        from wcs.ai import accounts
        keyboard = xbmc.Keyboard('', '{} · {}'.format(name, self.text(S_ENTER_KEY)))
        keyboard.doModal()
        if not keyboard.isConfirmed() or not keyboard.getText().strip():
            return
        key = keyboard.getText().strip()
        setting = accounts.key_setting(provider)
        previous = self.addon.getSetting(setting)
        self.status(self.text(S_CHECKING), 'busy')
        self.addon.setSetting(setting, key)
        try:
            valid = accounts.validate(provider)
        except Exception:
            valid = False
        if valid and self.signed_in():
            self.addon.setSetting(setting, previous)          # the account's copy comes back with fetch_secrets
            valid = self.save_to_account(provider, {'value': key}) == 'ok'
        if not valid:
            self.addon.setSetting(setting, previous)
            self.status(self.text(S_AI_BAD, name), 'error')
            return
        self.addon.setSetting('ai_provider', provider)
        accounts.sync_status(self.addon)
        position = self.getControl(AI_LIST).getSelectedPosition()
        self.show_ai()
        self.getControl(AI_LIST).selectItem(position)
        self.status(self.text(S_KEY_OK), 'ok')

    # Žánry
    def click_genres(self, control):
        if control == GENRES:
            item = self.getControl(GENRES).getSelectedItem()
            if item is None:
                return
            key = item.getProperty('ob.key')
            if key in self.chosen_genres:
                self.chosen_genres.discard(key)
                item.setProperty('ob.on', '')
            else:
                self.chosen_genres.add(key)
                item.setProperty('ob.on', '1')
            self.update_genres()
            self.prefetch.start(self.chosen_genres)          # the next step is fetched while the user chooses
        elif control == B1 and self.chosen_genres:
            self.addon.setSetting('onboarding_genres', ','.join(sorted(self.chosen_genres)))
            self.next_step()

    # Filmy, Seriály
    def click_movies(self, control):
        self.click_titles(control)

    def click_series(self, control):
        self.click_titles(control)

    def click_titles(self, control):
        media = self.media()
        if control == TITLES:
            box = self.getControl(TITLES)
            item = box.getSelectedItem()
            if item is None:
                return
            if item.getProperty('ob.more'):
                position = box.getSelectedPosition()
                pool = self.prefetch.pool(media, self.chosen_genres)
                self.status(self.text(S_LOADING_MOVIES if media == 'movie' else S_LOADING_SERIES), 'busy')
                cards = pool.fill(len(pool.cards) + picks.PAGE)
                services = pool.services(cards[position:])
                self.status()
                self.add_cards(box, cards, services, pool)
                box.selectItem(position)
                return
            tmdb = int(item.getProperty('ob.id'))
            if tmdb in self.chosen[media]:
                self.chosen[media].pop(tmdb)
                item.setProperty('ob.on', '')
            else:
                self.chosen[media][tmdb] = self.cards.get(tmdb)
                item.setProperty('ob.on', '1')
            self.update_titles()
            self.start_build(pause=True)                 # the first Pro tebe follows the answers (D26)
        elif control == B1:
            if self.step == 'movies':
                picks.save(list(self.chosen['movie'].values()), [])
                self.start_build()
                self.next_step()
            else:
                self.finish()

    # ------------------------------------------------------------------ moving on, the end

    def next_step(self):
        if self.single:
            self.close()
            return
        if not self.taste and state.finished() and state.has_key():
            self.finish_from_account()                   # finished meanwhile on the web (D32) or only the key was missing (D33)
            return
        following = plan.following(self.path(), self.step)
        if following is None:
            self.finish_from_account()
        else:
            self.show(following)

    def answers(self):
        """The films, series and genres chosen now (read by the build's thread: a tuple, never the dicts being changed);
        the genres are a weak taste signal of the build (D36), which reads them from the setting."""
        return (tuple(sorted(self.chosen['movie'])), tuple(sorted(self.chosen['tv'])), tuple(sorted(self.chosen_genres)))

    def start_build(self, pause=False):
        """The first Pro tebe from the answers so far, in the background (D14, D26): after every change of the films
        and the series (a short pause first), a build the newer answers make outdated stops early, so Dokončit mostly
        finds it ready and every try warms TMDb's cache for the next. No Webshare check; the service only adds the rows
        it lacks, what shows stays. The questionnaire alone (the first card of Pro tebe) builds once at its end, with
        the service's full build."""
        if self.taste:
            return
        self.wanted = self.answers()
        self.changed = time.time() if pause else 0.0
        if self.build is not None and self.build.is_alive():
            return                                       # the running build sees the change and builds again
        if self.built == self.wanted:
            return                                       # these answers are built already

        self.phase = ('taste', 0, 0)

        def report(phase, done=0, total=0):              # read by the window's thread (finish), never drawn here
            self.phase = (phase, done, total)

        def work():
            from wcs.foryou import engine
            monitor = xbmc.Monitor()
            while True:
                while time.time() - self.changed < SETTLE_S:  # the household is still picking
                    if monitor.waitForAbort(0.2):
                        return
                wanted = self.wanted
                started = time.time()
                try:
                    snapshot = engine.build(log=_log, verify=False, quick=True, progress=report,
                                            picks=[('movie', tmdb) for tmdb in wanted[0]] +
                                                  [('tv', tmdb) for tmdb in wanted[1]],
                                            cancelled=lambda: self.wanted != wanted)
                except engine.Cancelled:
                    _log('first Pro tebe outdated after {:.1f} s, again'.format(time.time() - started))
                    continue
                except Exception as exc:
                    _log('first Pro tebe failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
                    return
                if wanted != self.wanted:                # changed meanwhile: the newer answers
                    _log('first Pro tebe outdated after {:.1f} s, again'.format(time.time() - started))
                    continue
                engine.save(snapshot)
                self.built = wanted
                _log('first Pro tebe built in {:.1f} s ({} films, {} series)'.format(
                    time.time() - started, len(wanted[0]), len(wanted[1])))
                return

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

    def finish(self):
        picks.save([], list(self.chosen['tv'].values()))
        if self.taste:                                   # Pro tebe follows the new answers, with Kodi's progress
            self.close()
            from wcs.foryou import service as foryou_service
            foryou_service.build_now('questionnaire', visible=True)
            return
        self.status(self.text(S_BUILDING), 'busy')
        self.buttons()
        progress = xbmcgui.DialogProgressBG()
        progress.create(self.text(S_BUILDING), self.text(S_BUILDING))
        try:
            self.changed = 0.0                           # no pause any more: build now
            if self.build is None or (not self.build.is_alive() and self.built != self.answers()):
                self.start_build()
            from wcs.foryou.service import PHASES
            shown = None
            while self.build.is_alive():                 # what the first Pro tebe is doing, live (D13)
                phase = self.phase[0]
                if phase != shown:
                    shown = phase
                    start, string_id = PHASES.get(phase, (0, S_BUILDING))
                    message = self.addon.getLocalizedString(string_id)
                    if '{}' in message:
                        message = self.text(S_BUILDING)
                    progress.update(int(start * 0.8), self.text(S_BUILDING), message)
                    self.status(message, 'busy')
                xbmc.sleep(100)
            progress.update(85, self.text(S_BUILDING), self.text(S_BUILDING))
            settle_snapshot()
            state.remember(self.addon, state.DONE)       # before the rows: the first card is 'Upravit, co mám rád'
            prepare_rows()
            progress.update(100)
        finally:
            progress.close()
        state.remember(self.addon, state.DONE)
        self.finished = True
        self.close()


def settle_snapshot():
    """Pro tebe of the guide counts as built from the household's signals as they are now (the answers just stored):
    the service rebuilds it only for the usual reasons, never right after the guide (D26)."""
    from wcs.foryou import engine, service
    snapshot = engine.load()
    if snapshot is not None:
        snapshot['signals'] = service.signals_stamp()
        engine.save(snapshot)


def prepare_rows():
    """The first Pro tebe row with titles as a file before Home shows (D14, D26, rows are files:
    docs/plan/skin-optimization); the service builds the others once Home is up (measured on the TV: all eight 9.6 s)."""
    from wcs.skin import journal
    from wcs.skin.hero_contract import slot_count
    for slot in range(1, slot_count('foryou') + 1):
        params = journal.request_params('foryou', slot)
        if not params:
            continue
        try:
            if journal.prepare(params) and params.get('row') != 'fy_continue':    # Pokračovat is empty after the guide
                return
        except Exception as exc:
            _log('row foryou.{} not prepared: {}: {}'.format(slot, type(exc).__name__, exc), xbmc.LOGWARNING)


def restore_kodi_look():
    """D5: Kodi's own look (Estuary) again, nothing of Milionář on screen; the next start of the addon begins anew."""
    from wcs.skin import transition
    addon = xbmcaddon.Addon(ADDON_ID)
    state.cover(False)
    addon.setSetting(transition.COMPLETED, '')
    request = '{"jsonrpc":"2.0","id":1,"method":"Settings.SetSettingValue","params":{"setting":"lookandfeel.skin","value":"skin.estuary"}}'
    xbmc.executeJSONRPC(request)
    monitor = xbmc.Monitor()
    for _ in range(100):                                # Kodi asks to keep the look: yes
        if xbmc.getCondVisibility('Window.IsActive(yesnodialog)'):
            xbmc.executebuiltin('SendClick(11)')
            break
        if monitor.waitForAbort(0.1):
            break


def run(single=''):
    """Open the guide (or one key window, `single`: 'tmdb', 'webshare', 'ai'). The guide's end starts the service."""
    home = xbmcgui.Window(10000)
    from wcs.onboarding import launch
    if home.getProperty(launch.OPEN):
        return
    home.setProperty(launch.OPEN, '1')
    addon = xbmcaddon.Addon(ADDON_ID)
    try:
        guide = Guide(XML, addon.getAddonInfo('path'), 'Default', '1080i', single=single)
        guide.doModal()
        guide.stop_account()
        finished = guide.finished
        del guide
    finally:
        home.clearProperty(launch.OPEN)
    if finished:
        state.cover(False)
        home.setProperty(state.FINISHED, '1')
