# -*- coding: utf-8 -*-
"""Newest-first history of AI-recommended titles (feeds the skin's "Poslední doporučení" widget, 060 §6)."""
import json
import os
import time
import tempfile

import xbmcvfs

_FILE = os.path.join(
    xbmcvfs.translatePath('special://profile/addon_data/plugin.video.milionar/'), 'ai_recommendations.json')
MAX_ITEMS = 30


def load():
    try:
        with open(_FILE, 'r', encoding='utf-8') as handle:
            data = json.load(handle)
        return data if isinstance(data, list) else []
    except (OSError, ValueError):
        return []


def add(items):
    """Add matched recommendations (dicts with tmdb_id, media_type, title, year, poster, fanart, plot)."""
    wanted = [i for i in items if i.get('tmdb_id') and i.get('media_type') in ('movie', 'tv')]
    if not wanted:
        return
    previous = load()
    now = int(time.time())
    fresh = [dict(i, added=now) for i in wanted]
    keys = {(i['media_type'], str(i['tmdb_id'])) for i in fresh}
    kept = [i for i in previous if (i.get('media_type'), str(i.get('tmdb_id'))) not in keys]
    merged = (fresh + kept)[:MAX_ITEMS]
    # An identical ordered result should not manufacture a change via timestamps.
    content = lambda entries: [{k: v for k, v in i.items() if k != 'added'} for i in entries]
    if content(merged) == content(previous):
        return
    os.makedirs(os.path.dirname(_FILE), exist_ok=True)
    temporary = None
    try:
        with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=os.path.dirname(_FILE),
                                         suffix='.tmp', delete=False) as handle:
            temporary = handle.name
            json.dump(merged, handle, ensure_ascii=False, indent=1)
        os.replace(temporary, _FILE)
        temporary = None
    finally:
        if temporary:
            os.remove(temporary)
    from wcs.skin.refresh import changed
    changed({'widget_ai_recent'})
