# -*- coding: utf-8 -*-
"""Autoplay of the next episode and the collection offer (docs/plan/milionar-library/050 §4-5).

`plan(np)` decides what follows the current playback (pure given cached TMDb data; fetches only data a first
look needs). The tracker engine queues the next canonical URL in the Kodi playlist and shows the existing
countdown dialog; UI helpers here only build data.
"""
from datetime import date

import xbmcaddon

from wcs.library2 import meta, next_up, store, tmdb, urls

ADDON_ID = 'plugin.video.milionar'
DEFAULT_COUNTDOWN_S = 45
DEFAULT_TRIGGER_S = 15


def settings():
    """(enabled, countdown_seconds, trigger_seconds) from the existing autoplay settings, clamped like MyTV's monitor."""
    addon = xbmcaddon.Addon(ADDON_ID)
    enabled = (addon.getSetting('autoplay_enabled_global') or 'true') == 'true'
    try:
        countdown = max(10, min(120, int(addon.getSetting('autoplay_countdown_seconds') or DEFAULT_COUNTDOWN_S)))
        trigger = max(3, int(addon.getSetting('autoplay_trigger_seconds') or DEFAULT_TRIGGER_S))
    except ValueError:
        countdown, trigger = DEFAULT_COUNTDOWN_S, DEFAULT_TRIGGER_S
    if trigger >= countdown:
        trigger = max(3, countdown - 5)
    return enabled, countdown, trigger


def dialog_duration(remaining, countdown, trigger):
    """Seconds the countdown dialog runs: until `trigger` s before the end, at most countdown - trigger."""
    return int(max(3, min(remaining - trigger, countdown - trigger)))


def _season_data(show_id, show):
    seasons = {}
    for entry in show.get('seasons') or []:
        number = int(entry.get('season_number', 0))
        if number > 0:
            data = tmdb.season(show_id, number)
            if data:
                seasons[number] = data
    return seasons


def _rating(value):
    return '★ {:.1f}/10'.format(value) if value else ''


def plan(np, today=None, fetch=None):
    """What follows the playing item.

    Returns {'kind': 'series_next' | 'upcoming' | 'finished' | 'collection' | 'none', ...}:
      series_next  + 'canonical', 'title', 'season_episode', 'thumb', 'series_name', 'rating', 'year'
      upcoming     + 'season_episode', 'air_label' (the next episode exists but is not aired)
      finished     (last episode of an ended series)
      collection   + 'canonical', 'title', 'year', 'poster' (next unwatched released film of the collection)
    """
    today = today or date.today()
    if np.get('type') == 'episode':
        show_id = int(np['tmdb'])
        show = tmdb.show(show_id, fetch)
        if not show:
            return {'kind': 'none'}
        seasons = {n: meta.get(meta.key_season(show_id, n))[0] or {} for n in
                   (int(s.get('season_number', 0)) for s in show.get('seasons') or []) if n > 0}
        if len(seasons) and not all(seasons.values()):
            seasons = _season_data(show_id, show)
        order = next_up.episode_order(show, seasons, today)
        result = next_up.next_after(order, int(np['s']), int(np['e']), show.get('status'))
        ep = result['episode']
        if result['kind'] == 'next':
            return {'kind': 'series_next', 'canonical': urls.episode_url(show_id, ep['s'], ep['e']),
                    'title': ep['name'] or 'Epizoda {}'.format(ep['e']),
                    'season_episode': 'S{:02d}E{:02d}'.format(ep['s'], ep['e']),
                    'thumb': tmdb.POSTER + ep['still'] if ep.get('still') else '', 'series_name': show.get('name', ''),
                    'rating': _rating(show.get('vote_average')), 'year': (show.get('first_air_date') or '')[:4],
                    's': ep['s'], 'e': ep['e'], 'show_id': show_id}
        if result['kind'] == 'upcoming':
            return {'kind': 'upcoming', 'season_episode': 'S{:02d}E{:02d}'.format(ep['s'], ep['e']),
                    'air_label': next_up.air_label(ep['air_date'])}
        if result['kind'] == 'finished':
            return {'kind': 'finished'}
        return {'kind': 'none'}
    if np.get('type') == 'movie':
        movie = tmdb.movie(int(np['tmdb']), fetch)
        belongs = (movie or {}).get('belongs_to_collection') or {}
        if not belongs.get('id'):
            return {'kind': 'none'}
        collection = tmdb.collection(belongs['id'], fetch)
        if not collection:
            return {'kind': 'none'}
        ids = [p['id'] for p in collection.get('parts') or []]
        states = {i: (store.get_state('movie', i) or {}) for i in ids}
        part = next_up.next_in_collection(collection, int(np['tmdb']), states, today)
        if not part:
            return {'kind': 'none'}
        return {'kind': 'collection', 'canonical': urls.movie_url(part['id']), 'title': part.get('title', ''),
                'year': (part.get('release_date') or '')[:4], 'movie_id': part['id'],
                'collection_name': collection.get('name', '')}
    return {'kind': 'none'}
