# -*- coding: utf-8 -*-
"""A row of cards is a file Kodi reads itself (docs/plan/skin-optimization/010-native-rows.md).

Kodi starts a new Python for every plugin list asked for at the same time, about a second per row on a weak box, and a
change means a plugin call per row. A playlist needs no Python: `#EXTINF` gives a card's label, `#KODIPROP` every other
property, and the skin reads them with ListItem.Property. So:

  * the service writes the cards of a row to `rows/<name>.m3u`; the skin always points at the last file, also right
    after an update, and nothing has to run for a row to appear;
  * a row whose cards did not change is not touched: Kodi reloads a list only when its file name changes, so the file
    gets a new name (`rev`) only when the cards differ, and the old cards stay on screen until the new ones are there;
  * a changed title rewrites just its cards in the rows that show it (`apply_titles`).

Kodi's limits, all checked in the running Kodi 21:
  * a line longer than its 4096 byte buffer breaks the file: LINE_LIMIT, `_line`;
  * a playlist of one item is no directory: such a row holds the card twice and the skin caps the list (`limit` of the
    list's content), `cap`;
  * an item of a playlist has no art, watched state or resume point: `art.<type>`, `milionar.seen`, `milionar.resume`
    and `milionar.percent` carry them.
"""
import json
import os
import re
import threading
import time
import zlib

import xbmc
import xbmcgui
import xbmcvfs

ROOT = 'special://profile/addon_data/plugin.video.milionar/rows/'
LINE_LIMIT = 3900                        # bytes of a line of the file
# A card's click is its property milionar.exec. Kodi parses a list item's path for every label it draws, every frame,
# so the path stays short; its only job is to tell the cards apart: a reloaded list keeps its focus by the path.
SHORT_PATH = 'plugin://plugin.video.milionar/'
META = '#MILIONAR '                      # a comment for Kodi: {"count", "sig", "revision", "code"} of the row
NONE, ONE, MANY = '0', '1', '99'         # how many cards the list may show (Skin.String(mil.<sec>.<n>.cards))
REV = 'milionar.rowrev.{}'               # Home property: '.r<time>', part of the row's file name
ALIAS = 'milionar.rowalias.{}'           # Home property of a page's row file: its properties, 'file|limit' (`attach`)
OWNER = '.owner'                         # + a page's file property: the row it shows now
EXTINF = re.compile(r'^#EXTINF:-1,', re.M)
_lock = threading.Lock()
_titles = {}                             # 'movie:603' -> names of the row files that show it
_indexed = threading.Event()
_last = 0


def _folder():
    return xbmcvfs.translatePath(ROOT)


def path(name):
    return os.path.join(_folder(), name + '.m3u')


def url(name):
    return ROOT + name + '.m3u'


def key_of(props):
    """The title a card shows: a series for its episodes too."""
    tmdb = props.get('milionar.tmdb')
    kind = props.get('milionar.type')
    if not tmdb or kind not in ('movie', 'tv', 'episode'):
        return ''
    return '{}:{}'.format('movie' if kind == 'movie' else 'tv', tmdb)


# --------------------------------------------------------------------------- recorded item calls -> cards

def card(path_, calls):
    """(label, {property: text}, path) of one recorded item (wcs/skin/journal.py)."""
    label, props = '', {}
    for target, method, args, kwargs in calls:
        if target == 'new':
            label = args[0] if args else kwargs.get('label', '')
            second = args[1] if len(args) > 1 else kwargs.get('label2', '')
            if second:
                props['label2'] = second
        elif method == 'setLabel':
            label = args[0]
        elif method == 'setLabel2':
            props['label2'] = args[0]
        elif method == 'setProperty':
            props[str(args[0]).lower()] = args[1]
        elif method == 'setProperties':
            props.update((str(key).lower(), value) for key, value in args[0].items())
        elif method == 'setArt':
            props.update(('art.' + key, value) for key, value in args[0].items() if value)
        elif method == 'setPlaycount':
            props['milionar.seen'] = '1' if args and args[0] else ''
        elif method == 'setResumePoint':
            props.update(_resume(*args[:2]))
    return label, props, path_


def _resume(position=0, total=0):
    position, total = float(position or 0), float(total or 0)
    if position <= 0:
        return {'milionar.resume': '', 'milionar.percent': ''}
    return {'milionar.resume': '1', 'milionar.percent': str(int(100 * position / total)) if total else '0'}


def _line(text, what, name):
    if len(text.encode('utf-8')) <= LINE_LIMIT:
        return text
    xbmc.log('[Milionář Skin] {}: {} is too long for a row file, left out'.format(name, what), xbmc.LOGWARNING)
    return None


def _block(entry, name):
    label, props, path_ = entry
    lines = ['#EXTINF:-1,' + (' '.join(str(label).split()) or ' ')]
    for key, value in props.items():
        value = str(value if value is not None else '').replace('\r', ' ').replace('\n', '[CR]')
        if value:
            line = _line('#KODIPROP:{}={}'.format(key, value), key, name)
            if line:
                lines.append(line)
    lines.append('{}{:x}'.format(SHORT_PATH, zlib.crc32(str(path_).encode('utf-8'))))
    return lines


def text_of(cards, name=''):
    """The cards of the file; one card stands twice (the skin's list shows one)."""
    blocks = [line for entry in (cards * 2 if len(cards) == 1 else cards) for line in _block(entry, name)]
    return '\n'.join(blocks) + ('\n' if blocks else '')


# --------------------------------------------------------------------------- the file

def _meta(text):
    first = text.split('\n', 2)
    try:
        return json.loads(first[1][len(META):]) if len(first) > 1 and first[1].startswith(META) else {}
    except ValueError:
        return {}


def _body(text):
    return text.split('\n', 2)[2] if text.startswith('#EXTM3U\n' + META) and text.count('\n') >= 2 else ''


def read(name):
    try:
        with open(path(name), encoding='utf-8') as handle:
            return handle.read()
    except OSError:
        return None


def head(name):
    """What the row's file says about itself, without reading its cards: {} when there is none."""
    try:
        with open(path(name), encoding='utf-8') as handle:
            handle.readline()
            line = handle.readline()
    except OSError:
        return {}
    try:
        return json.loads(line[len(META):]) if line.startswith(META) else {}
    except ValueError:
        return {}


def _write(file_path, text):
    os.makedirs(os.path.dirname(file_path), exist_ok=True)
    temporary = '{}.{}.tmp'.format(file_path, threading.get_ident())
    with open(temporary, 'w', encoding='utf-8') as handle:
        handle.write(text)
    os.replace(temporary, file_path)


def _full(meta, body):
    return '#EXTM3U\n{}{}\n{}'.format(META, json.dumps(meta, separators=(',', ':')), body)


def _next():
    """Never the number before: two changes within a clock tick are two names."""
    global _last
    with _lock:
        _last = max(_last + 1, time.time_ns() // 10000000)
        return _last


def _renamed(name, rev_key, text):
    """The file under a new name: only that makes Kodi read it again. The one before stays for a list still reading
    it, older ones go."""
    home = xbmcgui.Window(10000)
    stamp = '.r{}'.format(_next())
    _write(path(name + stamp), text)
    prefix, keep = name + '.r', home.getProperty(REV.format(rev_key))
    home.setProperty(REV.format(rev_key), stamp)
    alias = home.getProperty(ALIAS.format(name)).split('|')[0]
    if alias and home.getProperty(alias + OWNER) == name:      # the page still shows this row
        home.setProperty(alias, name + stamp)
    try:
        for entry in os.scandir(_folder()):
            if entry.name.startswith(prefix) and entry.name.endswith('.m3u') \
                    and entry.name not in (name + stamp + '.m3u', name + keep + '.m3u'):
                os.remove(entry.path)
    except OSError:
        pass
    return stamp


def publish(name, cards, sig='', revision=None, rev_key=None, live=True, code=None):
    """Keep the cards of row file `name`. True when they differ from the file's: the list on screen reloads then
    (`live`; `rev_key`: its Home property, by default `name`). Equal cards only renew what the file says about itself."""
    body, old = text_of(cards, name), read(name)
    meta = {'count': len(cards), 'sig': sig, 'revision': revision, 'code': code}
    text = _full(meta, body)
    if old == text:
        return False
    changed = old is None or _body(old) != body
    _write(path(name), text)
    _index(name, body)
    if changed and live:
        _renamed(name, rev_key or slot_key(name), text)
    return changed


def cap(count):
    return NONE if not count else ONE if count == 1 else MANY


def attach(name, file_property, limit_property):
    """A row of a page (a detail, the genre page): it shows the row's last file at once, if there is one, and follows it
    from now on; `refresh` gives it new cards."""
    home = xbmcgui.Window(10000)
    if home.getProperty(file_property + OWNER) == name and home.getProperty(file_property) and head(name):
        return True                                    # it shows it already
    home.setProperty(ALIAS.format(name), '{}|{}'.format(file_property, limit_property))
    home.setProperty(file_property + OWNER, name)
    found = head(name)
    if found:
        home.setProperty(limit_property, cap(found.get('count')))
        home.setProperty(file_property, name)
    else:
        home.clearProperty(file_property)
    return bool(found)


def refresh(name, cards):
    """New cards of a row of a page; the limit changes first: a row of one card holds it twice."""
    home = xbmcgui.Window(10000)
    alias = home.getProperty(ALIAS.format(name)).split('|')
    if len(alias) == 2 and home.getProperty(alias[0] + OWNER) == name:
        home.setProperty(alias[1], cap(len(cards)))
    return publish(name, cards, rev_key=name)


def row_name(sec, slot, mode=''):
    return '{}.{}{}'.format(sec, slot, mode or '')


def clean():
    """At the start of the service the names of the last session are over: the base files are current."""
    home = xbmcgui.Window(10000)
    try:
        entries = list(os.scandir(_folder()))
    except OSError:
        return
    for entry in entries:
        found = re.match(r'(.+)\.r\d+\.m3u$', entry.name)
        if found or entry.name.endswith('.tmp'):
            try:
                os.remove(entry.path)
            except OSError:
                pass
        if found:
            home.clearProperty(REV.format(found.group(1)))


def forget(prefix, keep=300):
    """Rows of pages (a detail, the genre page) are a cache: only the last ones stay."""
    try:
        files = sorted((e for e in os.scandir(_folder()) if e.name.startswith(prefix) and e.name.endswith('.m3u')),
                       key=lambda e: e.stat().st_mtime, reverse=True)
        for entry in files[keep:]:
            os.remove(entry.path)
    except OSError:
        pass


# --------------------------------------------------------------------------- which rows show a title

PROPERTY = re.compile(r'^#KODIPROP:(milionar\.tmdb|milionar\.type)=(.*)$', re.M)


def _keys(body):
    found = {}
    for block in EXTINF.split(body):
        values = dict(PROPERTY.findall(block))
        key = key_of(values)
        if key:
            found[key] = True
    return found


def _index(name, body):
    keys = _keys(body)
    with _lock:
        for key, names in _titles.items():
            names.discard(name)
        for key in keys:
            _titles.setdefault(key, set()).add(name)


def index_all():
    """What the files on disk show (the service, once: the first change that needs it waits for this)."""
    try:
        entries = [entry.name[:-4] for entry in os.scandir(_folder()) if entry.name.endswith('.m3u')]
    except OSError:
        entries = []
    for name in entries:
        if not re.search(r'\.r\d+$', name):
            _index(name, _body(read(name) or ''))
    _indexed.set()


def rows_of(key):
    _indexed.wait(10)
    with _lock:
        return sorted(_titles.get(key, ()))


# --------------------------------------------------------------------------- one title changed

def _set_block(block, values):
    lines = [line for line in block.split('\n') if not any(line.startswith('#KODIPROP:{}='.format(key)) for key in values)]
    extra = ['#KODIPROP:{}={}'.format(key, value) for key, value in values.items() if value != '']
    return '\n'.join(lines[:1] + extra + lines[1:])


def patch(name, match, values_of):
    """Rewrite the cards `match(props)` accepts with `values_of(props)`: the row's order and other cards stay. The new
    text when the file changed, else False."""
    text = read(name)
    if not text:
        return False
    head_end = text.find('#EXTINF:')
    if head_end < 0:
        return False
    blocks = re.split(r'(?=^#EXTINF:)', text[head_end:], flags=re.M)
    changed = False
    for position, block in enumerate(blocks):
        props = dict(line[len('#KODIPROP:'):].split('=', 1) for line in block.split('\n')
                     if line.startswith('#KODIPROP:') and '=' in line)
        if block and match(props):
            updated = _set_block(block.rstrip('\n'), values_of(props)) + '\n'
            changed = changed or updated != block
            blocks[position] = updated
    if not changed:
        return False
    text = text[:head_end] + ''.join(blocks)
    _write(path(name), text)
    return text


def state_values(state):
    state = state or {}
    values = {'milionar.seen': '1' if int(state.get('playcount') or 0) > 0 else ''}
    position = state.get('resume_pos') if not values['milionar.seen'] else 0
    values.update(_resume(position, state.get('resume_total')))
    return values


def series_values(total, watched, started):
    values = {'watchedepisodes': str(watched) if total or watched else '', 'totalepisodes': str(total) if total else '',
              'numepisodes': str(total) if total else '', 'unwatchedepisodes': str(max(total - watched, 0)) if total else '',
              'milionar.begun': '1' if started or watched else '',
              'milionar.seen': '1' if total and watched >= total else ''}
    return values


HERO_BUTTON = re.compile(r'^milionar\.hero\.(?:s\d+\.)?b\d+$')   # a hero button's builtin, its own or of a lent layout


def _hero_state(props, texts, resumable, action):
    """The `milionar.hero.*` values of a card that follow its watch state: `texts` are what the row build's hero
    function made of the new state, written as hero.apply writes them (a field `texts` leaves out stays as it is). The
    hero says what the card's bar says, in the same write (Standa 2026-11-11: the bar moved, the hero kept the old time
    left); `action`: the play button's id."""
    from wcs.skin import hero
    from wcs.skin.performance import artwork
    values = {'milionar.hero.' + key: str(texts[key] or '') for key in hero.WATCH_FIELDS + ('left',) if key in texts}
    if 'milionar.hero.watchimage' in values:
        values['milionar.hero.watchimage'] = artwork(values['milionar.hero.watchimage'])
    values['milionar.hero.resumable'] = '1' if resumable else ''
    builtin = props.get('milionar.hero.do.' + action)
    label = xbmc.getLocalizedString(hero.S_CONTINUE if resumable else hero.S_PLAY)
    if builtin and label:                              # Pokračovat / Přehrát wherever the layout put that button
        values['milionar.hero.dl.' + action] = label
        values.update({key + 'l': label for key, value in props.items() if value == builtin and HERO_BUTTON.match(key)})
    return values


def _with_hero(values, texts_of, action):
    """values_of(props) of a patch: the card's own values and its hero's. `texts_of()`: (hero texts, resumable) of the
    new state or None, worked out once for all the title's cards; a hero that cannot be worked out stays as it was,
    the card never does."""
    memo = []

    def values_of(props):
        try:
            if not memo:
                memo.append(texts_of())
            return dict(values, **_hero_state(props, *memo[0], action=action)) if memo[0] else values
        except Exception as exc:
            memo[:] = [None]
            xbmc.log('[Milionář Skin] hero patch: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
            return values
    return values_of


def _title_patch(media, tmdb, data):
    """(match, values_of) for the cards of a changed film or series."""
    from wcs.library2 import rows, store
    from wcs.skin import hero
    tmdb = str(tmdb)
    if media == 'movie':
        values = state_values(store.get_state('movie', int(tmdb)))

        def movie_texts():
            card = rows.movie_card(data, int(tmdb))
            return hero.movie(card), bool(card['resume'])
        return (lambda props: props.get('milionar.type') == 'movie' and props.get('milionar.tmdb') == tmdb), \
            _with_hero(values, movie_texts, 'play')
    total, watched = rows.series_counts(data, int(tmdb))

    def series_texts():
        texts = hero.series(rows.series_card(data, int(tmdb)))
        return texts, texts['watchkind'] == 'resume'
    return (lambda props: props.get('milionar.type') == 'tv' and props.get('milionar.tmdb') == tmdb), \
        _with_hero(series_values(total, watched, bool(total or watched)), series_texts, 'next')


def _episode_patch(tmdb, season, episode, data):
    from wcs.library2 import rows, store
    from wcs.skin import hero
    state = store.get_state('tv', int(tmdb), int(season), int(episode)) or {}

    def episode_texts():
        card = rows.series_card(data, int(tmdb))
        found = next((e for e in card['order'] if e['s'] == int(season) and e['e'] == int(episode)), None)
        if found and not found['aired']:
            return None                                # not out yet: its hero keeps the air date
        texts = hero.episode(card, found or {'s': int(season), 'e': int(episode)}, state)
        if not found:
            texts.pop('watchimage')                    # no cached episode: its still stays
        return texts, texts['watchkind'] == 'resume'
    tmdb, season, episode = str(tmdb), str(season), str(episode)
    return (lambda props: props.get('milionar.type') == 'episode' and props.get('milionar.tmdb') == tmdb
            and props.get('milionar.s') == season and props.get('milionar.e') == episode), \
        _with_hero(state_values(state), episode_texts, 'play')


def _live(name):
    """A row file of a Pro tebe mode that is not chosen now is on no list."""
    found = re.match(r'^([a-z_]+)\.\d+(tv|movie)?$', name)
    if not found:
        return True
    return (found.group(2) or '') == xbmc.getInfoLabel('Skin.String(mil.{}.mode)'.format(found.group(1)))


def apply_titles(titles):
    """The cards of the changed titles [media, tmdb id, season, episode], at once and in every row file that shows
    them. Returns the names of the rows that changed."""
    from wcs.library2 import rows
    changed = {}
    data = rows.Data()                                 # the row build's own cache readers: no network
    for media, tmdb, season, episode in titles:
        key = '{}:{}'.format('movie' if media == 'movie' else 'tv', tmdb)
        names = rows_of(key)
        if not names:
            continue
        patches = [_title_patch('movie' if media == 'movie' else 'tv', tmdb, data)]
        if season is not None and episode is not None:
            patches.append(_episode_patch(tmdb, season, episode, data))
        for name in names:
            for match, values_of in patches:
                text = patch(name, match, values_of)
                if text:
                    changed[name] = text
    for name, text in changed.items():
        if _live(name):
            _renamed(name, slot_key(name), text)
    return sorted(changed)


class _Props(object):
    """The setProperty calls of wcs.services.store.apply, kept as card values."""

    def __init__(self):
        self.values = {}

    def setProperty(self, key, value):
        self.values[key] = value


def apply_services(keys):
    """The CZ service badges of titles whose services just arrived (jobs svc:<media>:<id>, wcs/services/store.py), at
    once and in every row file that shows them: a batch rewrites these cards, never every title row
    (docs/plan/skin-optimization/020, C1). Returns the names of the rows that changed."""
    from wcs.services import store
    found, _missing = store.lookup([pair for pair in (store.parse_key(k) for k in keys) if pair])
    changed = {}
    for found_key, services in found.items():
        media, tmdb = store.parse_key(found_key)
        movie, tmdb = media == 'movie', str(int(tmdb))
        props = _Props()
        store.apply(props, services)

        def match(card, movie=movie, tmdb=tmdb):
            return card.get('milionar.tmdb') == tmdb and (card.get('milionar.type') == 'movie') == movie
        for name in rows_of('{}:{}'.format('movie' if movie else 'tv', tmdb)):
            text = patch(name, match, lambda _card, values=props.values: values)
            if text:
                changed[name] = text
    for name, text in changed.items():
        if _live(name):
            _renamed(name, slot_key(name), text)
    return sorted(changed)


def slot_key(name):
    """The Home property of a row file: a slot's for every mode of its row (foryou.1tv -> foryou.1)."""
    found = re.match(r'^([a-z_]+\.\d+)(?:tv|movie)$', name)
    return found.group(1) if found else name
