# scrobble_delay.py - FINÁLNÍ OPRAVENÁ VERZE (spoleh na ListItem.Property + delší timeout)
import sys
import os
import re
import xbmc
import xbmcaddon
import urllib.parse
import json

from resources.lib.utils.log_utils import get_logger

log = get_logger()


def _parse_offline_episode_context(path: str):
    """Vrátí (series_folder, season, episode) z lokální cesty typu .../Series/Sezona X/SxxExx ..."""
    if not path:
        return None, None, None
    norm = path.replace('\\', '/')
    file_name = os.path.basename(norm)
    m = re.search(r'S(\d{1,2})E(\d{1,2})', file_name, flags=re.IGNORECASE)
    if not m:
        return None, None, None
    season_num = int(m.group(1))
    episode_num = int(m.group(2))

    series_folder = ''
    try:
        season_folder = os.path.dirname(norm)
        series_folder = os.path.basename(os.path.dirname(season_folder))
    except Exception:
        series_folder = ''
    return series_folder, season_num, episode_num


def _resolve_series_name_from_folder(folder_name: str):
    """Najde canonical series name v DB podle názvu složky (clean_filename match)."""
    if not folder_name:
        return None
    try:
        from resources.lib.database.metadata_db import db
        from resources.lib.utils.ui_utils import clean_filename
        target = clean_filename(folder_name).strip().lower()
        if not target or not db.conn:
            return None

        cur = db.conn.cursor()
        cur.execute('SELECT series_name, json_data FROM series_data')
        for series_name, json_data in cur.fetchall():
            try:
                if clean_filename(series_name).strip().lower() == target:
                    data = json.loads(json_data or '{}')
                    return (data.get('name') or series_name or '').strip() or None
                data = json.loads(json_data or '{}')
                data_name = (data.get('name') or '').strip()
                if data_name and clean_filename(data_name).strip().lower() == target:
                    return data_name
            except Exception:
                continue
    except Exception as e:
        log.warning(f'Offline resolve series failed: {e}')
    return None

# Pokud je payload už zamknutý, končíme (už byl spuštěn z play())
addon = xbmcaddon.Addon('plugin.video.mmirousek_v3')
if addon.getSetting('trakt_payload_locked') == 'true':
    log.info('Payload už zamknutý – končím (již spuštěno z play())')
    sys.exit(0)
    
try:
    if len(sys.argv) < 3:
        raise ValueError("Chybí argument cesty k addonu.")
   
    __addon_path__ = urllib.parse.unquote_plus(sys.argv[2])
    from resources.lib.history.scrobble import (
        scrobble_start,
        build_payload_from_id,
        build_episode_payload_from_db,
        lock_payload,
    )
    log.info('Import OK (resources.lib.history.scrobble)')
   
except Exception as e:
    log.error(f'CHYBA IMPORTU: {e}')
    sys.exit(1)

MAX_WAIT_SECONDS = 20  # Zvýšeno na 20 sekund – u Webshare streamů to někdy trvá déle
FALLBACK_DB_AFTER_ATTEMPT = 3


def _try_offline_db_fallback() -> bool:
    try:
        player_path = xbmc.Player().getPlayingFile() or xbmc.getInfoLabel('Player.FilenameAndPath') or ''
    except Exception:
        player_path = xbmc.getInfoLabel('Player.FilenameAndPath') or ''

    series_folder, season_num, episode_num = _parse_offline_episode_context(player_path)
    if not (series_folder and season_num is not None and episode_num is not None):
        return False

    canonical_series_name = _resolve_series_name_from_folder(series_folder)
    if not canonical_series_name:
        return False

    payload = build_episode_payload_from_db(canonical_series_name, int(season_num), int(episode_num))
    if not payload:
        return False

    try:
        lock_payload(payload, init_progress=0.0)
        scrobble_start(item=payload)
        return True
    except Exception as e:
        log.error(f'Offline fallback lock/start chyba: {e}')
        return False

for i in range(MAX_WAIT_SECONDS):
    
    tmdb_id = None
    mediatype = None
    
    # 1. Pokus o načtení z URL (pro úplnost, pokud by někdy fungovalo správně)
    if len(sys.argv) > 2:
        current_url = urllib.parse.unquote_plus(sys.argv[2])
        parsed = urllib.parse.urlparse(current_url)
        query_params = urllib.parse.parse_qs(parsed.query)
        url_tmdb = query_params.get('tmdb_id', [None])[0]
        url_media = query_params.get('mediatype', [None])[0]
        if url_tmdb and url_media:
            tmdb_id = url_tmdb
            mediatype = url_media
            log.info(f"Načteno z URL → tmdb_id={tmdb_id}, mediatype={mediatype}")

    # 2. Hlavní fallback: ListItem.Property (opakovaně – Kodi ho někdy nastaví až po chvíli)
    if not tmdb_id or not mediatype:
        list_tmdb = xbmc.getInfoLabel('ListItem.Property(tmdb_id)')
        list_media = xbmc.getInfoLabel('ListItem.Property(mediatype)')
        if list_tmdb and list_tmdb not in ('', '0'):
            tmdb_id = list_tmdb
        if list_media:
            mediatype = list_media
        log.info(f"Pokus {i+1}/{MAX_WAIT_SECONDS} – ListItem → tmdb_id={tmdb_id}, mediatype={mediatype}")

    # 3. Pokud máme platné ID, pokračujeme
    if tmdb_id and mediatype and tmdb_id not in ('', '0'):
        log.info(f'Spolehlivé ID NALEZENO po {i+1} pokusech: TMDB={tmdb_id}, Typ={mediatype}')
       
        payload = build_payload_from_id(tmdb_id, mediatype)
        
        if payload:
            try:
                addon = xbmcaddon.Addon('plugin.video.mmirousek_v3')
                
                addon.setSetting('trakt_last_payload', json.dumps(payload))
                addon.setSetting('trakt_payload_locked', 'true')
                
                log.info('Payload ULOŽEN + ZAMKNUT. Startuji scrobble_start().')
                scrobble_start()

                sys.exit(0)
            except Exception as e:
                log.error(f'CHYBA ZAMYKÁNÍ/STARTU: {e}')
                sys.exit(1)
        else:
            log.warning(f'Payload NELZE SESTAVIT pro ID {tmdb_id}.')
            sys.exit(1)

    if i + 1 >= FALLBACK_DB_AFTER_ATTEMPT:
        if _try_offline_db_fallback():
            sys.exit(0)

    xbmc.sleep(1000)

# Timeout vypršel
if _try_offline_db_fallback():
    sys.exit(0)

log.warning(f'Spolehlivé ID nenalezeno ani po {MAX_WAIT_SECONDS}s, vzdávám se.')
sys.exit(1)
