# -*- coding: utf-8 -*-
import os
import json
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import datetime
from xbmcvfs import translatePath
from resources.lib.utils.log_utils import get_logger
from resources.lib.utils.ui_utils import format_full_date_cz

log = get_logger()

from resources.lib.reports import streaming_report_generator
from resources.lib.tmdb import tmdb_utils
from resources.lib.tmdb.tmdb_kodi import set_video_info
from resources.lib.utils.ui_utils import pick_icon

ADDON = xbmcaddon.Addon()
PROFILE = translatePath(ADDON.getAddonInfo('profile'))
TOP10_JSON = os.path.join(PROFILE, 'streaming_top10.json')
CALENDAR_JSON = os.path.join(PROFILE, 'streaming_calendar.json')
TTL_HOURS = 24

def load_json(path):
    if not os.path.exists(path):
        return {}
    try:
        with open(path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        log.error(f"Failed to load JSON from {path}: {e}")
        return {}

def _needs_refresh(path, now):
    try:
        if not os.path.exists(path):
            return True
        mtime = datetime.datetime.fromtimestamp(os.path.getmtime(path))
        return (now - mtime).total_seconds() >= TTL_HOURS * 3600
    except Exception as e:
        log.error(f"Error checking refresh needs for {path}: {e}")
        return True

def refresh_report(force=False):
    now = datetime.datetime.now()
    if force or _needs_refresh(TOP10_JSON, now) or _needs_refresh(CALENDAR_JSON, now):
        log.info("Refreshing streaming report data.")
        streaming_report_generator.generate_all(TOP10_JSON, CALENDAR_JSON)
        ADDON.setSetting('last_report_refresh', now.isoformat())
    else:
        log.debug("Streaming report data is still fresh.")

def tmdb_poster_url(path):
    return f"https://image.tmdb.org/t/p/w500{path}" if path else ""

def extract_clean_title(raw_title: str) -> str:
    if not raw_title:
        return ""
    markers = [" TV Show", " Movie", " (season"]
    idx = len(raw_title)
    for m in markers:
        pos = raw_title.find(m)
        if pos != -1 and pos < idx:
            idx = pos
    return raw_title[:idx].strip()

def _parse_calendar_date(raw_date: str) -> datetime.datetime:
    if not raw_date:
        return datetime.datetime.today()
    raw_date = raw_date.strip()
    for fmt in ("%b %d %Y", "%b %d"):
        try:
            dt = datetime.datetime.strptime(raw_date, fmt)
            if fmt == "%b %d":
                dt = dt.replace(year=datetime.datetime.today().year)
            return dt
        except Exception as e:
            log.debug(f"Failed to parse date '{raw_date}' with format '{fmt}': {e}")
            continue
    log.warning(f"Could not parse calendar date: {raw_date}")
    return datetime.datetime.today()

def format_date_cz(raw_date: str) -> str:
    """Kalendář: datum jako 'Čtvrtek, 20. listopadu 2025'."""
    dt = _parse_calendar_date(raw_date)
    weekday_en = dt.strftime('%A')
    weekday_cz_map = {
        'Monday': 'Pondělí', 'Tuesday': 'Úterý', 'Wednesday': 'Středa',
        'Thursday': 'Čtvrtek', 'Friday': 'Pátek', 'Saturday': 'Sobota', 'Sunday': 'Neděle'
    }
    weekday_cz = weekday_cz_map.get(weekday_en, weekday_en)
    mon_en = dt.strftime('%b')
    mon_cz = MONTHS_CZ_GEN.get(mon_en, mon_en)
    return f"{weekday_cz}, {dt.day}. {mon_cz} {dt.year}"

def _pick_platform_icon(platform: str, fallback: str) -> str:
    p = (platform or '').lower().replace(' ', '').replace('+', 'plus')
    return pick_icon(ADDON, f"{p}.png", fallback)

# ------------------------------ MENU ------------------------------
def show_report_menu(handle, build_url):
    refresh_report(False)
    top10 = load_json(TOP10_JSON).get('top10', {})
    if not top10:
        xbmcgui.Dialog().notification('Streaming Report', 'Data nejsou dostupná.', xbmcgui.NOTIFICATION_WARNING)
        xbmcplugin.endOfDirectory(handle)
        return

    for platform in sorted(top10.keys()):
        url = build_url(action='streaming_report_platform', p=platform)
        li = xbmcgui.ListItem(label=platform)
        li.setArt({'icon': _pick_platform_icon(platform, 'DefaultFolder.png')})
        xbmcplugin.addDirectoryItem(handle, url, li, True)

    url = build_url(action='streaming_report_platform', p='calendar')
    li = xbmcgui.ListItem(label='Kalendář premiér')
    li.setArt({'icon': pick_icon(ADDON, 'calendar.png', 'DefaultCalendar.png')})
    xbmcplugin.addDirectoryItem(handle, url, li, True)

    xbmcplugin.endOfDirectory(handle)

# ------------------------------ TOP10 ------------------------------
def show_platform_titles(handle, build_url, platform):
    # Pro zobrazení klasického „seznam view“ explicitně nastavíme obsah na 'files'
    xbmcplugin.setContent(handle, "files")

    if platform == 'calendar':
        return show_calendar(handle, build_url)

    top10 = load_json(TOP10_JSON).get('top10', {}).get(platform, {})
    shows = top10.get('TV Shows', [])[:10]
    movies = top10.get('Movies', [])[:10]

    # Sekce: Seriály
    if shows:
        li_hdr = xbmcgui.ListItem(label='[COLOR blue]Seriály[/COLOR]')
        li_hdr.setArt({'icon': pick_icon(ADDON, 'tvshows.png', 'DefaultTvShows.png')})
        xbmcplugin.addDirectoryItem(handle, build_url(action='noop'), li_hdr, False)

        for idx, title in enumerate(shows, start=1):
            tv = tmdb_utils.search_tmdb_tv(title) or {}
            label = tv.get('title') or title
            year = ''
            genre = ''
            rating = None
            backdrop = None

            if tv.get('tmdb_id'):
                detail = tmdb_utils.get_tv_show_meta(int(tv['tmdb_id'])) or {}
                year = str(detail.get('year') or '')
                genres = detail.get('genres') or []
                genre = genres[0] if genres else ''
                backdrop = detail.get('backdrop_url')
                rating = detail.get('vote') or None

            extra = f" ({year})" if year else ''
            extra += f" ({genre})" if genre else ''
            if rating:
                extra += f" ★{rating:.1f}"

            poster = tmdb_poster_url(tv.get('poster_path'))
            rank_prefix = f"{idx}. "
            label2_txt = "{} · {}".format(platform, "Seriál")

            li = xbmcgui.ListItem(label=f"{rank_prefix}{label}{extra}", label2=label2_txt)
            # Navigační položka: žádné IsPlayable; folder → True
            if poster:
                li.setArt({'icon': poster, 'thumb': poster, 'poster': poster, 'fanart': backdrop or poster})
            else:
                li.setArt({'icon': _pick_platform_icon(platform, 'DefaultTvShowTitle.png')})

            # U folderu mediatype neuvádíme → skiny snáze použijí „seznam“ view
            info = {
                'title': label,
                'plot': tv.get('overview', ''),
                'year': int(year) if year.isdigit() else 0,
                'genre': genre or ''
            }
            if rating is not None:
                info['rating'] = float(rating)
            set_video_info(li, info)

            # Seriál → Series Manager (adresář)
            url = build_url(action='series_search', what=title)
            xbmcplugin.addDirectoryItem(handle, url, li, True)

    # Sekce: Filmy
    if movies:
        li_hdr = xbmcgui.ListItem(label='[COLOR orange]Filmy[/COLOR]')
        li_hdr.setArt({'icon': pick_icon(ADDON, 'movies.png', 'DefaultMovies.png')})
        xbmcplugin.addDirectoryItem(handle, build_url(action='noop'), li_hdr, False)

        for idx, title in enumerate(movies, start=1):
            mv = tmdb_utils.search_tmdb_movie(title) or {}
            label = mv.get('title') or title
            year = ''
            genre = ''
            rating = None
            backdrop = None

            if mv.get('tmdb_id'):
                detail = tmdb_utils.get_movie_meta(int(mv['tmdb_id'])) or {}
                year = str(detail.get('year') or '')
                genres = detail.get('genres') or []
                genre = genres[0] if genres else ''
                rating = detail.get('vote') or None
                backdrop = detail.get('backdrop_url')

            extra = f" ({year})" if year else ''
            extra += f" ({genre})" if genre else ''
            if rating:
                extra += f" ★{rating:.1f}"

            poster = tmdb_poster_url(mv.get('poster_path'))
            rank_prefix = f"{idx}. "
            label2_txt = "{} · {}".format(platform, "Film")

            li = xbmcgui.ListItem(label=f"{rank_prefix}{label}{extra}", label2=label2_txt)
            # Navigační položka: žádné IsPlayable; folder → True
            if poster:
                li.setArt({'icon': poster, 'thumb': poster, 'poster': poster, 'fanart': backdrop or poster})
            else:
                li.setArt({'icon': _pick_platform_icon(platform, 'DefaultMovieTitle.png')})

            info = {
                'title': label,
                'plot': mv.get('overview', ''),
                'year': int(year) if year.isdigit() else 0,
                'genre': genre or ''
            }
            if rating is not None:
                info['rating'] = float(rating)
            set_video_info(li, info)

            # Film → Webshare search (adresář)
            q = f"{title} {year}" if year else title
            url = build_url(action='search', q=q)
            xbmcplugin.addDirectoryItem(handle, url, li, True)

    xbmcplugin.endOfDirectory(handle)

# ------------------------------ KALENDÁŘ ------------------------------
def show_calendar(handle, build_url):
    # Pro zobrazení klasického „seznam view“ explicitně nastavíme obsah na 'files'
    xbmcplugin.setContent(handle, "files")

    calendar = load_json(CALENDAR_JSON).get('calendar', [])
    if not calendar:
        xbmcgui.Dialog().notification('Kalendář', 'Žádná data.', xbmcgui.NOTIFICATION_INFO)
        xbmcplugin.endOfDirectory(handle)
        return

    grouped = {}
    for event in calendar:
        raw_day = event.get('release_date', '') or ''
        dt = _parse_calendar_date(raw_day)
        key = dt.strftime("%Y-%m-%d")
        lst = grouped.setdefault(key, {"dt": dt, "raw": raw_day, "events": []})
        lst["events"].append(event)

    sorted_keys = sorted(grouped.keys(), key=lambda k: grouped[k]["dt"], reverse=True)
    for key in sorted_keys:
        raw_day = grouped[key]["raw"]
        cz_day = format_full_date_cz(raw_day)

        li_hdr = xbmcgui.ListItem(label=f"[COLOR gold]{cz_day}[/COLOR]")
        li_hdr.setArt({'icon': pick_icon(ADDON, 'calendar.png', 'DefaultCalendar.png')})
        xbmcplugin.addDirectoryItem(handle, build_url(action='noop'), li_hdr, False)

        for event in grouped[key]["events"]:
            raw_title = event.get('title', 'Neznámý')
            clean_title = extract_clean_title(raw_title)
            platform = event.get('platform', '')
            media_type = (event.get('type', '') or '').lower()

            label = clean_title
            year = ''
            genre = ''
            backdrop = None
            rating = None
            poster = ''
            plot = ''
            mediatype_is_movie = 'movie' in media_type

            if mediatype_is_movie:
                mv = tmdb_utils.search_tmdb_movie(clean_title) or {}
                label = mv.get('title') or clean_title
                if mv.get('tmdb_id'):
                    detail = tmdb_utils.get_movie_meta(int(mv['tmdb_id'])) or {}
                    year = str(detail.get('year') or '')
                    genres = detail.get('genres') or []
                    genre = genres[0] if genres else ''
                    backdrop = detail.get('backdrop_url')
                    rating = detail.get('vote') or None
                poster = tmdb_poster_url(mv.get('poster_path'))
                plot = mv.get('overview', '')
                # Film → Webshare search
                q = f"{clean_title} {year}" if year else clean_title
                url = build_url(action='search', q=q)
                is_folder = True
            else:
                tv = tmdb_utils.search_tmdb_tv(clean_title) or {}
                label = tv.get('title') or clean_title
                if tv.get('tmdb_id'):
                    detail = tmdb_utils.get_tv_show_meta(int(tv['tmdb_id'])) or {}
                    year = str(detail.get('year') or '')
                    genres = detail.get('genres') or []
                    genre = genres[0] if genres else ''
                    backdrop = detail.get('backdrop_url')
                    rating = detail.get('vote') or None
                poster = tmdb_poster_url(tv.get('poster_path'))
                plot = tv.get('overview', '')
                # Seriál → Series Manager
                url = build_url(action='series_search', what=clean_title)
                is_folder = True

            extra = f" ({year})" if year else ''
            extra += f" ({genre})" if genre else ''
            if rating is not None:
                extra += f" ★{rating:.1f}"

            label2_txt = "{} · {}".format(platform, event.get("type", ""))
            li = xbmcgui.ListItem(label=f"{label}{extra}", label2=label2_txt)
            # Navigační položka: žádné IsPlayable; folder → True
            if poster:
                li.setArt({'icon': poster, 'thumb': poster, 'poster': poster, 'fanart': backdrop or poster})
            else:
                li.setArt({'icon': _pick_platform_icon(platform, 'DefaultVideo.png')})

            info = {
                'title': label,
                'plot': plot,
                'year': int(year) if year.isdigit() else 0,
                'genre': genre or ''
            }
            if rating is not None:
                info['rating'] = float(rating)
            set_video_info(li, info)

            xbmcplugin.addDirectoryItem(handle, url, li, is_folder)

    xbmcplugin.endOfDirectory(handle)