# -*- coding: utf-8 -*-
"""The services of a title in the one cache of the addon (`meta` in library.db, docs/plan/genre-browser/080).

Key `svc:<media>:<id>`, the CZ block of TMDb `{media}/{id}/watch/providers` in the compact form of catalog.compact,
kept 7 days (setting services_ttl_days); "runs nowhere" is an answer too ({}), an error never is. Rows read many titles
at once (`lookup`, one query, in the row's snapshot: wcs/library2/rows._services); what is missing or expired is fetched
by the service in the background (`request`, job `svc:<media>:<id>`) and the rows showing titles reload once a batch
is in (wcs/skin/service.py, refresh.SERVICE_ROWS). A TMDb detail asked with `append_to_response=watch/providers`
(Pro tebe) fills the cache for free (`from_details`).
"""
import xbmc

from wcs.services import catalog

KEY = 'svc:{}:{}'
DAY = 86400
TTL = 7 * DAY                       # the default of the addon setting services_ttl_days (resources/settings.xml)
MEDIA = {'movie': 'movie', 'tv': 'tv', 'series': 'tv'}


def ttl():
    """How long a title's services are fresh: the addon setting, TTL when it cannot be read."""
    try:
        import xbmcaddon
        days = int(float(xbmcaddon.Addon('plugin.video.milionar').getSetting('services_ttl_days')))
    except Exception:
        return TTL
    return days * DAY if days > 0 else TTL


def key(media, tmdb_id):
    return KEY.format(MEDIA.get(media, media), int(tmdb_id))


def parse_key(name):
    """(media, id) of a job / cache key 'svc:movie:603', or None."""
    parts = (name or '').split(':')
    if len(parts) == 3 and parts[0] == 'svc' and parts[1] in ('movie', 'tv') and parts[2].isdigit():
        return parts[1], int(parts[2])
    return None


def lookup(pairs):
    """({key: services} of the cached titles (an expired entry is served too), [keys missing or expired])."""
    from wcs.library2 import meta
    keys = list(dict.fromkeys(key(m, i) for m, i in pairs if i))
    try:
        found = meta.get_many_status(keys)
    except Exception as exc:
        xbmc.log('[Milionář Služby] cache read failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
        return {}, []
    services = {k: value for k, (value, _stale) in found.items() if isinstance(value, dict)}
    return services, [k for k in keys if k not in found or found[k][1]]


def store(media, tmdb_id, region_block):
    """The title's services, cached when the database lets us: a write that waited out the lock (six fetches at once,
    "database is locked" in the guide on Windows Kodi) keeps the answer TMDb gave, like wcs/metadata/TMDbCache."""
    from wcs.library2 import meta
    data = catalog.compact(region_block)
    try:
        meta.put(key(media, tmdb_id), data, ttl())
    except Exception as exc:
        xbmc.log('[Milionář Služby] cache write failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
    return data


def from_details(details):
    """{'movie:603': services} of [(media, id, detail)] that brought their services along, stored in one write."""
    from wcs.library2 import meta
    entries, found, fresh = [], {}, ttl()
    for media, tmdb_id, detail in details:
        block = (detail or {}).get('watch/providers')
        if not isinstance(block, dict):
            continue
        data = catalog.compact((block.get('results') or {}).get(catalog.REGION))
        entries.append((key(media, tmdb_id), data, fresh))
        found['{}:{}'.format(MEDIA.get(media, media), int(tmdb_id))] = data
    if entries:
        meta.put_many(entries)
    return found


def fetch(media, tmdb_id):
    """Ask TMDb for one title's services and store them; None when TMDb did not answer (nothing is stored)."""
    from wcs.foryou import api
    media = MEDIA.get(media, media)
    try:
        data = (api.FETCH or api._http)('{}/{}/watch/providers'.format(media, int(tmdb_id)), {})
    except Exception as exc:
        api._count('failed')
        xbmc.log('[Milionář Služby] {} {} failed: {}: {}'.format(media, tmdb_id, type(exc).__name__, exc),
                 xbmc.LOGWARNING)
        return None
    if not isinstance(data, dict):
        api._count('failed')
        return None
    api._count('network')
    return store(media, tmdb_id, (data.get('results') or {}).get(catalog.REGION))


def ensure(pairs, workers=6):
    """{key: services} of `pairs` [(media, id)]: the cache, the missing ones fetched now (in parallel). For a caller
    that prepares a view anyway (the genre page); the Home rows never wait for the network (`request`)."""
    from wcs.foryou import api
    found, missing = lookup(pairs)
    todo = [parse_key(k) for k in missing]
    for (media, tmdb_id), data in zip(todo, api.parallel([lambda p=p: fetch(*p) for p in todo], workers)):
        if data is not None:
            found[key(media, tmdb_id)] = data
    return found


def request(keys):
    """Let the service fetch these titles' services in the background (deduplicated there; job svc:<media>:<id>)."""
    if keys:
        from wcs.skin import refresh
        refresh.notify('skin_widget_refresh', keys)


def apply(item, services):
    """ListItem properties of the badge (gen_cinema CARD_POSTER) and of the detail."""
    logos, more = catalog.badges(services)
    for n in range(catalog.BADGES):
        item.setProperty('milionar.svc.{}'.format(n + 1), logos[n] if n < len(logos) else '')
    item.setProperty('milionar.svc.more', more)
    item.setProperty('milionar.svc.class', str(catalog.class_of(services)))
