import sys
from urllib.parse import parse_qsl

# Skin widgets take a fast path: they must not import the whole router (docs/plan/skin-milionar/060 §2)
_params = dict(parse_qsl(sys.argv[2][1:])) if len(sys.argv) > 2 else {}
_action = _params.get('action', '')

# Anything but a row of Home is something the user started: the service's background work steps aside for it
if not _action.startswith('widget_') and _action != 'skin_detail_row' and __name__ == '__main__':
    from wcs.skin import userfirst
    userfirst.mark()

# The addon runs in Kodi's reused Python interpreter (addon.xml <reuselanguageinvoker>): the widget fast path stays
# warm between calls (no interpreter start per Home row), everything else gets fresh modules exactly as before.
_WARM_ACTIONS = ('widget_', 'mlist', 'mupcoming', 'mplay', 'skin_run', 'skin_detail_row')
_WARM_MODULES = ('wcs.skin.widgets', 'wcs.skin.row_cache', 'wcs.skin.refresh', 'wcs.skin.performance', 'wcs.skin.detail', 'wcs.library2',
                 'wcs.skin.journal', 'wcs.skin.userfirst')


def _manage_modules():
    import os
    root = os.path.dirname(os.path.abspath(__file__))
    purge_all = False
    if os.path.islink(os.path.join(os.path.dirname(root), 'skin.milionar')):     # development: edits must show up
        newest = 0.0
        for folder, _, names in os.walk(os.path.join(root, 'wcs')):
            for name in names:
                if name.endswith('.py'):
                    newest = max(newest, os.stat(os.path.join(folder, name)).st_mtime)
        purge_all = newest > getattr(sys, '_milionar_code_stamp', newest)
        sys._milionar_code_stamp = newest
    warm = _action.startswith(_WARM_ACTIONS)
    for name in list(sys.modules):
        if name == 'wcs' or name.startswith('wcs.'):
            if purge_all or not (warm and name.startswith(_WARM_MODULES)):
                if name != 'wcs':
                    del sys.modules[name]


# A Home row: the service prepared it (wcs/skin/journal.py), this call only hands it over. Nothing else is imported.
_served = False
if _action == 'widget_row' and __name__ == '__main__':
    from wcs.skin import journal
    _params = journal.normalize(_params)               # also the limit of cards per Home row
    _served = journal.serve(int(sys.argv[1]), _params)

if not _served:
    _manage_modules()

if __name__ == '__main__' and not _served:
    from wcs.skin.context import install_listing_context
    install_listing_context(_params)
    from wcs.skin import local
    if local.run(_params, int(sys.argv[1])):
        pass                                           # one of the quick actions: done the one way they are done
    elif _action == 'skin_detail_row':
        from wcs.skin import detail
        detail.run(int(sys.argv[1]), _params)
    elif _action == 'show_wcs_details':
        from wcs import router                         # another skin: the addon's own details dialog
        router.router(sys.argv[2][1:])
    elif _action.startswith('vinyl_'):
        from wcs.vinyl import actions                  # the listings (wcs.skin.local.LISTINGS)
        actions.run(int(sys.argv[1]), _params)
    elif _action == 'milionar_demo':
        # one title of the offline Millionaire demo, opened from the Milionář Home widgets (wcs/games/demo)
        from wcs.games.demo import launch
        launch.run(_params)
    elif _action == 'library_migrate':
        from wcs.library2 import migration
        migration.run(_params)
    elif (_action.startswith('widget_') and _action != 'widget_row') or _action == 'skin_run':
        from wcs.skin import widgets
        widgets.run(int(sys.argv[1]), _params)
    elif _action == 'mplay':
        # canonical play URL (docs/plan/milionar-library/040 §2): no router import, resolving must be quick
        from wcs.library2 import resolver
        resolver.run(int(sys.argv[1]), _params)
    elif _action in ('tmdb_added_movies', 'tmdb_added_series'):
        # the addon menu's old My movies / My series screens are the new fast listings now (060, 2026-10-01)
        from wcs.library2 import listings
        listings.run(int(sys.argv[1]), {'kind': 'movies' if _action == 'tmdb_added_movies' else 'series'})
    elif _action == 'widget_row':
        import time
        import xbmcgui
        _started = time.perf_counter()
        # temporary (docs/plan/skin-optimization): Window(Home).Property(milionar.perf.delay) = ms added to every row,
        # to see on a fast machine what a weak box shows
        _delay = xbmcgui.Window(10000).getProperty('milionar.perf.delay')
        if _delay.isdigit():
            time.sleep(int(_delay) / 1000.0)
        from wcs.library2 import rows
        rows.run(int(sys.argv[1]), _params)
        from wcs.skin import perflog
        perflog.log('row {}.{} {} built in {:.0f} ms'.format(_params.get('sec', ''), _params.get('slot', ''), _params.get('row', ''),
                                                             (time.perf_counter() - _started) * 1000))
    elif _action == 'mlist':
        # My movies / My series listings (060): fast path, no router import (a cancelled slow script can crash Kodi)
        from wcs.library2 import listings
        listings.run(int(sys.argv[1]), _params)
    elif _action == 'mupcoming':
        from wcs.library2 import listings
        listings.upcoming(int(sys.argv[1]), _params)
    else:
        import xbmc
        from wcs import router
        # Player monitor se registruje automaticky při prvním použití (singleton pattern)
        # Předčasná registrace může způsobovat interferenci
        router.router(sys.argv[2][1:])
