#!/usr/bin/python
# -*- coding: utf-8 -*-

import xbmc
import xbmcaddon
import time
import datetime

def migrate_ai_models(addon):
    """Přepne uložené AI/TTS modely, které už nejsou v nabídce, na aktuální výchozí."""
    try:
        from wcs.ai.model_catalog import migrate_model_settings
        for setting_id, old, new in migrate_model_settings(addon):
            xbmc.log(f"[Milionář Service] Model {setting_id}: {old} -> {new}", level=xbmc.LOGINFO)
    except Exception as e:
        xbmc.log(f"[Milionář Service] Migrace modelů selhala: {e}", level=xbmc.LOGERROR)


def main():
    """Autostart service pro doplněk Milionář"""
    xbmc.log("[Milionář Service] Spouštím se při startu Kodi", level=xbmc.LOGINFO)
    
    try:
        # Zkontrolovat existenci doplňku
        addon = xbmcaddon.Addon('plugin.video.milionar')
        xbmc.log("[Milionář Service] Doplňek nalezen", level=xbmc.LOGINFO)
        
        # Jednorázový návrat nastavení na výchozí hodnoty; při běžném startu jen jedno čtení nastavení
        from wcs.defaults import enforce_addon_defaults
        if enforce_addon_defaults(addon):
            addon = xbmcaddon.Addon('plugin.video.milionar')           # settings se změnily
        migrate_ai_models(addon)
        from wcs.ai import accounts
        accounts.sync_status(addon)                                    # stav přihlášení v nastavení podle uložených klíčů
        
        # Zkontrolovat nastavení autostart
        auto_start = addon.getSetting('auto_start_enabled')
        if auto_start == 'true':
            # Načíst čas čekání z nastavení (default 1 sekunda)
            try:
                delay_seconds = int(addon.getSetting('auto_start_delay_seconds') or '1')
            except (ValueError, TypeError):
                delay_seconds = 1
            
            xbmc.log(f"[Milionář Service] Autostart zapnut - čekám {delay_seconds} sekund", level=xbmc.LOGINFO)
            
            # Počkat podle nastavení
            xbmc.sleep(delay_seconds * 1000)  # Převod na milisekundy
            
            # Načíst akci z nastavení
            auto_start_action = addon.getSetting('auto_start_action')
            
            # Načíst nastavení notifikací
            show_notifications = addon.getSetting('auto_start_show_notifications')
            
            if auto_start_action == '0':  # Spustit doplněk
                xbmc.executebuiltin('RunAddon(plugin.video.milionar)')
                if show_notifications == 'true':
                    notification_text = addon.getLocalizedString(32197)
                    xbmc.executebuiltin(f'Notification(Milionář, {notification_text}, 3000)')
                xbmc.log("[Milionář Service] Doplňek spuštěn", level=xbmc.LOGINFO)
            elif auto_start_action == '1':  # Otevřít MyTV
                xbmc.executebuiltin('RunPlugin(plugin://plugin.video.milionar/?action=my_tv_dialog)')
                if show_notifications == 'true':
                    notification_text = addon.getLocalizedString(32209)
                    xbmc.executebuiltin(f'Notification(Milionář, {notification_text}, 3000)')
                xbmc.log("[Milionář Service] Dialog MyTV spuštěn", level=xbmc.LOGINFO)
            elif auto_start_action == '2':  # Otevřít MyCinema
                xbmc.executebuiltin('RunPlugin(plugin://plugin.video.milionar/?action=my_cinema_dialog)')
                if show_notifications == 'true':
                    notification_text = addon.getLocalizedString(32220)
                    xbmc.executebuiltin(f'Notification(Milionář, {notification_text}, 3000)')
                xbmc.log("[Milionář Service] Dialog MyCinema spuštěn", level=xbmc.LOGINFO)
            else:
                xbmc.log("[Milionář Service] Neznámá akce autostartu", level=xbmc.LOGWARNING)
        else:
            xbmc.log("[Milionář Service] Autostart vypnut", level=xbmc.LOGINFO)
        
        # VIP kontrola se provádí PO autostartu (nezávisle na tom, zda je zapnutý)
        xbmc.log("[Milionář Service] Začínám VIP kontrolu", level=xbmc.LOGINFO)
        check_vip_expiration(addon)
            
    except Exception as e:
        xbmc.log(f"[Milionář Service] Chyba: {e}", level=xbmc.LOGERROR)

def check_vip_expiration(addon):
    """Kontrola VIP expirace Webshare účtu při autostartu"""
    try:
        # Import WebshareClient pro použití existující funkce
        from wcs.webshare.WebshareClient import refresh_vip_info
        
        # Použít existující funkci s show_warning=True pro zobrazení varování
        refresh_vip_info(addon, show_warning=True, log_context="autostart_service")
        xbmc.log("[Milionář Service] VIP kontrola dokončena", level=xbmc.LOGINFO)
        
    except Exception as e:
        xbmc.log(f"[Milionář Service] VIP kontrola selhala: {e}", level=xbmc.LOGERROR)
        xbmc.executebuiltin(f'Notification(Milionář, VIP kontrola selhala: {e}, 3000)')



def start_skin_installer():
    """Install/update skin.milionar and offer the switch, without delaying the rest of the service."""
    try:
        import threading
        import xbmcgui
        from wcs.skin.installer import run
        def install():
            try:
                run()
            finally:
                xbmcgui.Window(10000).clearProperty('milionar.skin.installing')
            try:                                      # an update started from the settings menu: finish its window
                from wcs.skin import update
                update.resume()
            except Exception as exc:
                xbmc.log(f"[Milionář Update] resume failed: {exc}", level=xbmc.LOGERROR)
        xbmcgui.Window(10000).setProperty('milionar.skin.installing', '1')
        threading.Thread(target=install, name='milionar-skin-installer', daemon=True).start()
    except Exception as e:
        xbmc.log(f"[Milionář Service] Instalace skinu selhala: {e}", level=xbmc.LOGERROR)


def start_skin_properties():
    """Publish row revisions independently of the network builders."""
    try:
        import threading
        from wcs.skin.service import run
        threading.Thread(target=run, name='milionar-skin-props', daemon=True).start()
    except Exception as e:
        xbmc.log(f"[Milionář Service] Vlastnosti skinu selhaly: {e}", level=xbmc.LOGERROR)


def start_foryou():
    """Pro tebe recommendations (docs/plan/pro-tebe): rebuild the snapshot when it is due."""
    try:
        import threading
        from wcs.foryou import service as foryou_service
        threading.Thread(target=foryou_service.run, name='milionar-foryou', daemon=True).start()
    except Exception as e:
        xbmc.log(f"[Milionář Service] Pro tebe selhalo: {e}", level=xbmc.LOGERROR)


def start_library_tracker():
    """Playback tracker of the addon library (docs/plan/milionar-library 040): own thread, events queued from Kodi callbacks."""
    try:
        import threading
        from wcs.library2 import tracker
        threading.Thread(target=tracker.run, name='milionar-tracker', daemon=True).start()
    except Exception as e:
        xbmc.log(f"[Milionář Service] Tracker selhal: {e}", level=xbmc.LOGERROR)



def run_dev_harness():
    """Live harness listener (scripts/dialog_harness/kodi_live.py, scripts/game_harness); idles unless harness/ENABLED
    exists. Blocks until Kodi exits. Release builds strip this function and its call (scripts/build_zip.sh)."""
    try:
        from wcs.devtools import harness_service
        harness_service.run_listener()
    except Exception as e:
        xbmc.log(f"[Milionář Service] Harness listener selhal: {e}", level=xbmc.LOGERROR)



if __name__ == '__main__':
    from wcs.playback import language
    language.start()
    # Home gets the CPU first on slow devices: the playback tracker is only needed once something plays
    import threading
    _tracker_start = threading.Timer(10, start_library_tracker)
    _tracker_start.daemon = True
    _tracker_start.start()
    start_skin_installer()
    start_skin_properties()
    start_foryou()
    main()
    run_dev_harness()
    # Player callbacks need this thread even when the release strips the dev harness.
    xbmc.Monitor().waitForAbort()
