# -*- coding: utf-8 -*-
"""Skin search flow (docs/plan/skin-milionar/070): keyboard -> history -> one TMDb /search/multi -> cache -> window 1120.

All network access happens once per search, here. The window's rows only read
skin_cache/search_current.json (widgets.py) and native library paths.
"""
import json
import os
import time
from urllib.parse import quote

import xbmc
import xbmcaddon
import xbmcgui

ADDON_ID = 'plugin.video.milionar'
HISTORY_FILE = 'search_history_universal.json'
HISTORY_MAX = 15
TMDB_IMG = 'https://image.tmdb.org/t/p/w500'
CACHE_NAME = 'search_current'
S_HEADING = 32234     # "Search"
S_NOT_CONFIGURED = 32237


def _cache_file():
    profile = xbmcaddon.Addon(ADDON_ID).getAddonInfo('profile')
    from xbmcvfs import translatePath
    return os.path.join(translatePath(profile), 'skin_cache', CACHE_NAME + '.json')


def library_paths(query):
    """Rows "In My movies" / "In My series": the addon's own lists filtered by the query (090), through widget_row."""
    def path(row):
        return 'plugin://plugin.video.milionar/?action=widget_row&row={}&q={}&limit=40'.format(row, quote(query, safe=''))
    return path('search_my_movies'), path('search_my_series')


def _entry(row):
    kind = row.get('media_type')
    if kind == 'person':
        department = row.get('known_for_department') or ''
        if department == 'Directing':
            run = 'action=display_director_dialog&director_id={}'.format(row.get('id'))
        elif department == 'Writing':
            run = 'action=display_writer_dialog&writer_id={}&writer_name={}'.format(
                row.get('id'), quote(row.get('name', '')))
        else:
            run = 'action=display_actor_dialog&actor_id={}&media_type=movie&person_type=actor'.format(row.get('id'))
        return {'kind': 'person', 'title': row.get('name', ''), 'plot': department, 'run': run,
                'poster': TMDB_IMG + row['profile_path'] if row.get('profile_path') else ''}
    date = row.get('release_date') or row.get('first_air_date') or ''
    tmdb_type = 'movie' if kind == 'movie' else 'tv'
    return {'kind': 'movie' if kind == 'movie' else 'tv',
            'title': row.get('title') or row.get('name') or '', 'year': date[:4], 'tmdb_id': row.get('id'),
            'plot': row.get('overview', ''), 'rating': row.get('vote_average'),
            'poster': TMDB_IMG + row['poster_path'] if row.get('poster_path') else '',
            'run': 'action=show_wcs_details&media_type={}&tmdb_id={}'.format(tmdb_type, row.get('id'))}


def fetch(addon, query):
    import requests
    from wcs.metadata.TMDbClient import get_tmdb_api_key
    response = requests.get('https://api.themoviedb.org/3/search/multi', params={
        'api_key': get_tmdb_api_key(addon), 'language': 'cs-CZ', 'query': query}, timeout=10)
    response.raise_for_status()
    rows = [r for r in response.json().get('results', []) if r.get('media_type') in ('movie', 'tv', 'person')]
    return [_entry(r) for r in rows]


def write_cache(query, entries):
    path = _cache_file()
    os.makedirs(os.path.dirname(path), exist_ok=True)
    tmp = path + '.tmp'
    with open(tmp, 'w', encoding='utf-8') as handle:
        json.dump({'query': query, 'built': int(time.time()), 'items': entries}, handle, ensure_ascii=False)
    os.replace(tmp, path)


def run(addon, params):
    query = (params.get('query') or '').strip()
    if not query:
        keyboard = xbmc.Keyboard('', addon.getLocalizedString(S_HEADING))
        keyboard.doModal()
        if not keyboard.isConfirmed():
            return
        query = keyboard.getText().strip()
    if not query:
        return
    from wcs import user_data
    user_data.store_search_history(query, addon.getAddonInfo('profile'), HISTORY_FILE, HISTORY_MAX)
    xbmc.executebuiltin('ActivateWindow(busydialognocancel)')
    try:
        try:
            entries = fetch(addon, query)
        except ValueError:      # no TMDb key: the library rows still work
            entries = []
            xbmcgui.Dialog().notification('Milionář', addon.getLocalizedString(S_NOT_CONFIGURED),
                                          xbmcgui.NOTIFICATION_INFO, 4000)
        except Exception as exc:
            xbmc.log('[Milionář Skin] search failed: {}: {}'.format(type(exc).__name__, exc), xbmc.LOGWARNING)
            entries = []
        write_cache(query, entries)
        movies, shows = library_paths(query)
        home = xbmcgui.Window(10000)
        home.setProperty('milionar.search.query', query)
        home.setProperty('milionar.search.lib_movies', movies)
        home.setProperty('milionar.search.lib_tvshows', shows)
        home.setProperty('milionar.search.token', str(int(time.time() * 1000)))
    finally:
        xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
    if not xbmc.getCondVisibility('Window.IsActive(1120)'):
        xbmc.executebuiltin('ActivateWindow(1120)')
