# -*- coding: utf-8 -*-
"""Which row the hero reads (wcs/skin/hero_source.py + gen_cinema): the generated conditions, evaluated like Kodi does
on random Home states, must give exactly what the model says - the current row when it has items, else the first row
with a title, the borrowed buttons of an emptied current row - for every field, state and button of every section.

Run: python3 -m unittest scripts/skin_harness/test_hero_source.py -v   (from the addon folder)
    python3 scripts/skin_harness/test_hero_source.py OLD.xml          # also compare with an older generated file
"""
import os
import random
import re
import sys
import types
import unittest
from unittest.mock import patch

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, '..', '..'))
for name in ('xbmc', 'xbmcgui'):
    sys.modules.setdefault(name, types.ModuleType(name))
import gen_cinema  # noqa: E402
from wcs.skin import hero_source  # noqa: E402

FIELDS = ('title', 'kicker', 'plot', 'left', 'rating', 'play', 'detail', 'title_image', 'size', 'badge', 'now', 'meta',
          'watchimage', 'watchstatus', 'watchtitle', 'watchtime', 'watchpercent', 'watchkind',
          'b1', 'b2', 'b3', 'b4', 'b1l', 'b2l', 'b3l', 'b4l', 'b1i')


# --------------------------------------------------------------------------- a small Kodi condition evaluator

def definitions(text):
    exps = dict(re.findall(r'<expression name="([^"]+)">(.*?)</expression>', text))
    variables = {}
    for name, body in re.findall(r'<variable name="([^"]+)">(.*?)</variable>', text, re.S):
        variables[name] = re.findall(r'<value(?: condition="([^"]*)")?>(.*?)</value>', body)
    return exps, variables


class State(object):
    def __init__(self, props, containers):
        self.props, self.containers = props, containers       # containers: {lid: {'n': items, 'item': {prop: v}}}

    def info(self, label):
        if label == 'Container(9000).ListItem.Property(id)':              # the Home menu's section
            return self.props.get('menu', '')
        m = re.match(r'Window\(Home\)\.Property\((.+)\)$', label)
        if m:
            return self.props.get(m.group(1), '')
        m = re.match(r'Container\((\d+)\)\.NumItems$', label)
        if m:
            return str(self.containers.get(m.group(1), {}).get('n', 0))
        m = re.match(r'Container\((\d+)\)\.ListItem\.(?:Property\((.+)\)|(\w+))$', label)
        if m:
            c = self.containers.get(m.group(1), {})
            if not c.get('n'):
                return ''
            return str(c.get('item', {}).get(m.group(2) or m.group(3), ''))
        return self.props.get(label, '')

    def leaf(self, text):
        text = text.strip()
        if text in ('true', 'false'):
            return text == 'true'
        m = re.match(r'String\.IsEqual\((.+),([^,]*)\)$', text)
        if m:
            return self.info(m.group(1)).lower() == m.group(2).lower()
        m = re.match(r'String\.IsEmpty\((.+)\)$', text)
        if m:
            return self.info(m.group(1)) == ''
        m = re.match(r'Integer\.IsGreater\((.+),(\d+)\)$', text)
        if m:
            value = self.info(m.group(1))
            return int(value or 0) > int(m.group(2))
        m = re.match(r'Container\((\d+)\)\.ListItem\.(\w+)$', text)          # boolean item flags (IsResumable)
        if m:
            return bool(self.info(text))
        raise ValueError('unknown leaf: ' + text)


def tokens(text):
    out, depth, word = [], 0, ''
    for ch in text:
        if depth == 0 and ch in '+|![]':
            if word.strip():
                out.append(word.strip())
            word = ''
            out.append(ch)
            continue
        if ch == '(':
            depth += 1
        elif ch == ')':
            depth -= 1
        word += ch
    if word.strip():
        out.append(word.strip())
    return out


def evaluate(text, state, exps, seen=()):
    while '$EXP[' in text:
        text = re.sub(r'\$EXP\[([^\]]+)\]', lambda m: '[' + exps['MilCine' + m.group(1)[7:]] + ']'
                      if m.group(1).startswith('MilCine') else m.group(0), text)
    items = tokens(text)
    pos = [0]

    def peek():
        return items[pos[0]] if pos[0] < len(items) else None

    def take():
        pos[0] += 1
        return items[pos[0] - 1]

    def factor():
        tok = take()
        if tok == '!':
            return not factor()
        if tok == '[':
            value = orexp()
            assert take() == ']'
            return value
        return state.leaf(tok)

    def andexp():
        value = factor()
        while peek() == '+':
            take()
            value = factor() and value
        return value

    def orexp():
        value = andexp()
        while peek() == '|':
            take()
            value = andexp() or value
        return value
    result = orexp()
    assert pos[0] == len(items), text
    return result


def value_of(name, state, exps, variables):
    for condition, text in variables['MilCine' + name]:
        if not condition or evaluate(condition, state, exps):
            return re.sub(r'\$INFO\[([^\]]+?)\]', lambda m: state.info(m.group(1)), text)
    return ''


# --------------------------------------------------------------------------- random Home states and the model

def random_state(sec, rnd):
    base = gen_cinema.entry(sec)[0]
    containers, slots = {}, []
    for n in gen_cinema.slot_numbers(sec):
        lid = str(gen_cinema.list_id(sec, n))
        count = rnd.choice([0, 0, 3, 3, 3])
        titled = rnd.random() < 0.6
        item = {}
        if titled:
            for field in FIELDS:
                if rnd.random() < 0.8:
                    item['milionar.hero.' + field] = '{}-{}-{}'.format(field, n, rnd.randint(0, 9))
            item['milionar.hero.title'] = 'T{}'.format(n)
            item['milionar.hero.size'] = rnd.choice(['l', 'm', 's'])
            item['milionar.hero.b1i'] = rnd.choice(['play', ''])
            item['IsResumable'] = rnd.choice(['', '1'])
            item['PercentPlayed'] = '40'
        containers[lid] = {'n': count, 'item': item}
        slots.append((n, lid, titled))
    # rows without titles lend their layout to the items of the rows with titles (hero_buttons.lent)
    for n, lid, titled in slots:
        if titled:
            for k, _other, other_titled in slots:
                if k != n and not other_titled and rnd.random() < 0.5:
                    item = containers[lid]['item']
                    item['milionar.hero.s{}'.format(k)] = '1'
                    for field in hero_source.LENT_FIELDS:
                        item['milionar.hero.s{}.{}'.format(k, field)] = 'lent{}-{}-{}'.format(k, field, n)
                    item['milionar.hero.s{}.b1i'.format(k)] = rnd.choice(['play', ''])
    current = rnd.choice([''] + [lid for _n, lid, _t in slots])
    props = {'milionar.row.' + sec: current, 'menu': gen_cinema.entry(sec)[1]}
    return slots, containers, props, base


def watch(sec, slots, containers, props):
    """What the skin's onfocus and the watcher (wcs/skin/hero_source.py) leave in the Home properties."""
    current = props['milionar.row.' + sec]
    rows = [(lid, containers[lid]['n'] > 0, containers[lid]['n'] > 0 and bool(containers[lid]['item'].get('milionar.hero.title')))
            for _n, lid, _t in slots]
    chosen = hero_source.choose(current, rows)
    out = dict(props)
    if chosen:
        out[hero_source.SOURCE.format(sec)] = chosen
    slot = hero_source.lent_slot(current, chosen, {lid: n for n, lid, _t in slots})
    item = containers.get(chosen, {}).get('item', {})
    if slot and item.get('milionar.hero.s{}'.format(slot)):
        out[hero_source.LENT.format(sec)] = 'true'
        for field in hero_source.LENT_FIELDS:
            out['{}.{}'.format(hero_source.LENT.format(sec), field)] = item.get('milionar.hero.s{}.{}'.format(slot, field), '')
    return out, chosen, slot


def model(sec, slots, containers, props):
    """The hero by the rule (docs/plan/skin-milionar/190, 220): fields of the source item, buttons of the lending row."""
    _out, chosen, slot = watch(sec, slots, containers, props)
    item = containers.get(chosen, {}).get('item', {}) if chosen else {}
    lent = bool(slot and item.get('milionar.hero.s{}'.format(slot)))
    fields = {}
    for name, label in gen_cinema.FIELDS.items():
        fields[name] = item.get(label.split('Property(')[1].rstrip(')'), '')
    for n in gen_cinema.BUTTONS:
        for suffix, key in (('', 'b{}'), ('Label', 'b{}l')):
            prop = key.format(n)
            fields['B{}{}'.format(n, suffix)] = item.get('milionar.hero.s{}.{}'.format(slot, prop) if lent else 'milionar.hero.' + prop, '')
    return chosen, fields


class HeroSourceTest(unittest.TestCase):
    def test_the_hero_never_shows_a_row_the_cursor_is_not_on(self):
        rows = [('1', True, True), ('2', True, False), ('3', False, False)]
        self.assertEqual(hero_source.choose('2', rows), '2')           # a card that is no title keeps its own hero
        self.assertEqual(hero_source.choose('3', rows), '1')           # an emptied row
        self.assertEqual(hero_source.choose('', rows), '1')            # nothing current yet

    def test_film_inline_progress_and_episode_preview_are_mutually_exclusive_even_with_stale_fields(self):
        exps, _ = definitions(gen_cinema.build())
        for sec in set(gen_cinema.SECTIONS) - {'vinyl'}:
            lid = str(gen_cinema.list_id(sec, 1))
            for media in ('movie', 'episode', 'tv'):
                item = {'milionar.hero.title': 'Title', 'milionar.type': media, 'milionar.resume': '1',
                        'milionar.hero.watchkind': 'resume', 'milionar.hero.watchpercent': '50'}
                state = State({'milionar.hero.' + sec: lid}, {lid: {'n': 1, 'item': item}})
                self.assertEqual(evaluate(exps['MilCineMovieProgress_' + sec], state, exps), media == 'movie')
                self.assertEqual(evaluate(exps['MilCineHasWatch_' + sec], state, exps), media != 'movie')

    def test_conditions_match_the_model(self):
        text = gen_cinema.build()
        exps, variables = definitions(text)
        rnd = random.Random(7)
        for sec in gen_cinema.SECTIONS:
            for _ in range(250):
                slots, containers, props, _base = random_state(sec, rnd)
                props, chosen, _slot = watch(sec, slots, containers, props)
                state = State(props, containers)
                expected_source, fields = model(sec, slots, containers, props)
                feeding = [lid for n, lid, _t in slots if evaluate(exps['MilCineIs_{}_{}'.format(sec, n)], state, exps)]
                self.assertEqual(feeding, [expected_source] if expected_source else [], sec)
                self.assertEqual(evaluate(exps['MilCineAny_' + sec], state, exps), bool(expected_source))
                for name, wanted in fields.items():
                    if 'MilCine{}_{}'.format(name, sec) in variables:
                        self.assertEqual(value_of('{}_{}'.format(name, sec), state, exps, variables), wanted, (sec, name))
                item = containers.get(expected_source, {}).get('item', {}) if expected_source else {}
                for n in gen_cinema.BUTTONS:
                    self.assertEqual(evaluate(exps['MilCineHasB{}_{}'.format(n, sec)], state, exps),
                                     bool(fields['B{}'.format(n)]), (sec, n))
                self.assertEqual(evaluate(exps['MilCineHasTitleImage_' + sec], state, exps),
                                 bool(item.get('milionar.hero.title_image')))
                for suffix, prop in (('HasWatch', 'watchkind'), ('HasWatchProgress', 'watchpercent')):
                    self.assertEqual(evaluate(exps['MilCine{}_{}'.format(suffix, sec)], state, exps),
                                     bool(item.get('milionar.hero.' + prop)))

    def test_the_watcher_leaves_what_the_model_says(self):
        rnd = random.Random(3)

        class Window(object):
            def __init__(self, _id=0):
                pass

            def getProperty(self, name):
                return live.props.get(name, '')

            def setProperty(self, name, value):
                live.props[name] = value

            def clearProperty(self, name):
                live.props.pop(name, None)
        strings = {}

        def info(label):
            m = re.match(r'Skin\.String\((.+)\)$', label)
            if m:
                return strings.get(m.group(1), '')
            m = re.match(r'Container\((\d+)\)\.CurrentItem$', label)
            if m:
                return '1'
            return live.info(label)
        for name, function in (('getInfoLabel', info), ('getCondVisibility', lambda condition: live.leaf(condition))):
            replacement = patch.object(hero_source.xbmc, name, function, create=True)
            replacement.start()
            self.addCleanup(replacement.stop)
        watcher = hero_source.Watcher.__new__(hero_source.Watcher)
        watcher.home, watcher.lent_key = Window(), {}
        for sec in gen_cinema.SECTIONS:
            live = State({}, {})
            for step in range(150):
                slots, containers, props, _base = random_state(sec, rnd)
                strings = {'mil.{}.{}.type'.format(sec, n): 'row' for n, _lid, _t in slots}
                kept = {k: v for k, v in live.props.items() if k.startswith('milionar.hero.')}
                live = State(dict(props, **kept), containers)
                if step % 3 == 0 and props['milionar.row.' + sec]:     # a row with a title sets it on focus (ROW)
                    lid = props['milionar.row.' + sec]
                    if containers[lid]['item'].get('milionar.hero.title'):
                        live.props[hero_source.SOURCE.format(sec)] = lid
                watcher.lent_key = {}                          # a new state: the item under the cursor changed
                watcher.tick(sec)
                wanted, _chosen, _slot = watch(sec, slots, containers, props)
                got = {k: v for k, v in live.props.items() if k.startswith('milionar.hero.')}
                self.assertEqual(got, {k: v for k, v in wanted.items() if k.startswith('milionar.hero.')}, (sec, step))

    def test_nothing_changes_under_a_modal_dialog(self):
        """The update window, the settings menu, a context menu: Container(<id>) answers from the dialog, so the watcher
        must not look (it took every row for empty and switched the hero off, Standa 2026-11-09)."""
        self.assertIn('!System.HasActiveModalDialog', hero_source.SCREEN)

        class Monitor(object):
            waits = 0

            def abortRequested(self):
                return False

            def waitForAbort(self, _seconds):
                Monitor.waits += 1
                return Monitor.waits >= 3

        family = types.ModuleType('wcs.skin.family')
        family.active = lambda: True
        paging = types.ModuleType('wcs.skin.paging')
        paging.tick = lambda sec: ticked.append(('paging', sec))
        for modal in (True, False):
            ticked = []
            Monitor.waits = 0
            screen = lambda condition: condition == hero_source.SCREEN and not modal
            with patch.dict(sys.modules, {'wcs.skin.family': family, 'wcs.skin.paging': paging}), \
                    patch('wcs.skin.family', family, create=True), patch('wcs.skin.paging', paging, create=True), \
                    patch.object(hero_source.xbmc, 'getCondVisibility', screen, create=True), \
                    patch.object(hero_source.xbmc, 'log', lambda *a, **k: None, create=True), \
                    patch.object(hero_source, '_on_screen', lambda: 'foryou'), \
                    patch.object(hero_source, 'Watcher', lambda: types.SimpleNamespace(
                        tick=lambda sec: ticked.append(('hero', sec)))):
                hero_source.run(Monitor())
            if modal:
                self.assertEqual(ticked, [], 'a modal dialog is open: no tick touches the hero or the rows')
            else:
                self.assertIn(('hero', 'foryou'), ticked)
                self.assertIn(('paging', 'foryou'), ticked)

    def test_the_genre_page_has_a_section_hero(self):
        import gen_genre
        exps, variables = definitions(gen_cinema.build() + gen_genre.build())
        rnd = random.Random(5)
        for _ in range(300):
            slots, containers, props, _base = random_state('genre', rnd)
            props, _chosen, _slot = watch('genre', slots, containers, props)
            props.update({'milionar.genre.active': 'true', 'milionar.genre.owner': 'mil_foryou', 'menu': 'mil_foryou',
                          'milionar.genre.name': 'Válečný', 'milionar.genre.kicker': 'FILMY'})
            state = State(props, containers)
            expected_source, fields = model('genre', slots, containers, props)
            self.assertTrue(evaluate(exps['MilCineAny_genre'], state, exps))               # the buttons always stay
            self.assertEqual(value_of('Title_genre', state, exps, variables), fields['Title'] if expected_source else 'Válečný')
            self.assertEqual(value_of('Kicker_genre', state, exps, variables), fields['Kicker'] if expected_source else 'FILMY')
            self.assertEqual(value_of('Plot_genre', state, exps, variables), fields['Plot'])
            sizes = [step for step, _f, _l in gen_cinema.TITLE_FONTS if evaluate(exps['MilCineSize_{}_genre'.format(step)], state, exps)]
            self.assertLessEqual(len(sizes), 1)

    def test_a_page_belongs_to_its_section(self):
        """The detail and the genre page show only in the section they were opened in; the menu leads back into them."""
        text = gen_cinema.build()
        exps, _variables = definitions(text)
        menus = list(gen_cinema.gen_slots.MENU_IDS.values())
        right = re.search(r'<include name="MilCineMenuRight">(.*?)</include>', text, re.S).group(1)
        targets = re.findall(r'<onright condition="([^"]*)">SetFocus\(([^)]*)\)</onright>', right)
        rnd = random.Random(9)
        for _ in range(400):
            menu = rnd.choice(menus)
            detail, genre = rnd.choice(['', 'true']), rnd.choice(['', 'true'])
            props = {'menu': menu, 'milionar.detail.active': detail, 'milionar.detail.owner': rnd.choice(menus),
                     'milionar.genre.active': genre, 'milionar.genre.owner': rnd.choice(menus)}
            state = State(props, {})
            detail_here = detail == 'true' and props['milionar.detail.owner'] == menu
            genre_here = genre == 'true' and props['milionar.genre.owner'] == menu and not detail_here
            self.assertEqual(evaluate(exps['MilCineDetailHere'], state, exps), detail_here)
            self.assertEqual(evaluate(exps['MilCineGenreHere'], state, exps), genre_here)
            self.assertEqual(evaluate(exps['MilCineOverlayHere'], state, exps), detail_here or genre_here)
            chosen = [target for condition, target in targets if evaluate(condition, state, exps)]
            self.assertEqual(chosen, ['41000'] if detail_here else ['43000'] if genre_here else ['$PARAM[target]'])

    def test_the_conditions_grow_with_the_slots_not_their_square(self):
        text = gen_cinema.build()
        self.assertNotIn('MilCineUse_', text)
        self.assertLess(len(text), 1000000)
        exps, _variables = definitions(text)
        for sec in gen_cinema.SECTIONS:
            self.assertLess(len(exps['MilCineIs_{}_{}'.format(sec, 1)]), 200)


def compare_with(path, rounds=300):
    """Old generated file vs the model (the old conditions decided the same things on their own)."""
    old = open(path, encoding='utf-8').read()
    exps, variables = definitions(old)
    rnd = random.Random(11)
    differences = 0
    for sec in gen_cinema.SECTIONS:
        for _ in range(rounds):
            slots, containers, props, _base = random_state(sec, rnd)
            state = State(props, containers)                   # the old skin needs no watcher
            expected_source, fields = model(sec, slots, containers, props)
            feeding = [lid for n, lid, _t in slots if evaluate(exps['MilCineIs_{}_{}'.format(sec, n)], state, exps)]
            if feeding != ([expected_source] if expected_source else []):
                differences += 1
                continue
            for name, wanted in fields.items():
                if 'MilCine{}_{}'.format(name, sec) in variables and value_of('{}_{}'.format(name, sec), state, exps, variables) != wanted:
                    differences += 1
                    print('differs', sec, name)
                    break
    print('old file vs model: {} differences in {} states'.format(differences, rounds * len(gen_cinema.SECTIONS)))
    return differences


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1].endswith('.xml'):
        sys.exit(1 if compare_with(sys.argv.pop(1)) else 0)
    unittest.main()
