# -*- coding: utf-8 -*-
"""Live test provider (docs/plan/milionar-library/120 §3): local ffmpeg videos instead of Webshare / Kraska.

Active only when the hidden setting `dev_fixture_provider` is on AND the harness ENABLED flag exists, so
it can never trigger for a normal user. The resolver (L1) asks `file_for()`; `seed_meta()` pre-fills the
TMDb cache from scripts/library_harness/fixtures/tmdb_fixture.json so no network is needed.
"""
import json
import os

ADDON_ID = 'plugin.video.milionar'
LONG, SHORT = 'fixture_long.mp4', 'fixture_short.mp4'


def _addon_dir():
    return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def _harness_dir():
    return os.path.join(_addon_dir(), 'scripts', 'library_harness')


def enabled():
    try:
        import xbmcaddon
        import xbmcvfs
        if xbmcaddon.Addon(ADDON_ID).getSetting('dev_fixture_provider') != 'true':
            return False
        flag = os.path.join(xbmcvfs.translatePath('special://profile/addon_data/{}/harness/'.format(ADDON_ID)), 'ENABLED')
        return os.path.exists(flag)
    except Exception:
        return False


def file_for(media_type, tmdb_id, season=None, episode=None):
    """Path of the test video for a title: the last episode / second fixture film is the short one."""
    short = (media_type == 'movie' and int(tmdb_id) == 900102) or (media_type == 'episode' and int(episode or 0) % 2 == 0)
    path = os.path.join(_harness_dir(), 'media', SHORT if short else LONG)
    return path if os.path.exists(path) else None


def load_fixture():
    with open(os.path.join(_harness_dir(), 'fixtures', 'tmdb_fixture.json'), 'r', encoding='utf-8') as handle:
        return json.load(handle)


def _shifted(data, days):
    """Fixture dates (frozen "today" 2026-06-15) moved by `days`, so live tests see unaired episodes relative to now."""
    from datetime import date, timedelta

    def move(text):
        try:
            year, month, day = (int(x) for x in text[:10].split('-'))
            return (date(year, month, day) + timedelta(days=days)).isoformat()
        except (ValueError, TypeError):
            return text

    def walk(node):
        if isinstance(node, dict):
            for key, value in node.items():
                if key in ('air_date', 'first_air_date', 'release_date') and isinstance(value, str):
                    node[key] = move(value)
                else:
                    walk(value)
        elif isinstance(node, list):
            for value in node:
                walk(value)
    walk(data)
    return data


def seed_meta(now=None, relative_to_today=False):
    """Write the fixture TMDb data into meta with a long TTL; returns the number of keys.

    relative_to_today=True shifts every date so the fixture's frozen day becomes the real today (live tests)."""
    from datetime import date
    from wcs.library2 import meta
    data = load_fixture()
    if relative_to_today:
        data = _shifted(data, (date.today() - date.fromisoformat(data['today'])).days)
    ttl = 365 * 86400
    count = 0
    for tmdb_id, show in data['tv'].items():
        meta.put(meta.key_tv(tmdb_id), show, ttl, now)
        count += 1
    for key, season in data['season'].items():
        show_id, number = key.split(':')
        meta.put(meta.key_season(show_id, number), season, ttl, now)
        count += 1
    for tmdb_id, movie in data['movie'].items():
        meta.put(meta.key_movie(tmdb_id), movie, ttl, now)
        count += 1
    for cid, collection in data['collection'].items():
        meta.put(meta.key_collection(cid), collection, ttl, now)
        count += 1
    return count
