# -*- coding: utf-8 -*-
"""Original (usually English) title of a movie/series, for searching and matching
Webshare files named "Friends.S01E02..." when the addon knows only "Přátelé".

Kodi library first (local JSON-RPC), then TMDb details (cached for a week).
"""

import json

import xbmc

CACHE_SECONDS = 7 * 24 * 3600


def _from_library(media_type, title, year=''):
    if media_type == 'tv':
        method, key = 'VideoLibrary.GetTVShows', 'tvshows'
    else:
        method, key = 'VideoLibrary.GetMovies', 'movies'
    query = {'jsonrpc': '2.0', 'id': 1, 'method': method,
             'params': {'properties': ['originaltitle', 'year'],
                        'filter': {'field': 'title', 'operator': 'is', 'value': title}}}
    try:
        items = json.loads(xbmc.executeJSONRPC(json.dumps(query))).get('result', {}).get(key, [])
    except (ValueError, TypeError):
        return ''
    for item in items:
        if year and str(item.get('year', '')) not in ('', '0', str(year)[:4]):
            continue
        if item.get('originaltitle'):
            return item['originaltitle']
    return ''


def _from_tmdb(media_type, tmdb_id, title, year=''):
    import requests
    from wcs.metadata import TMDbCache
    from wcs.metadata.TMDbLogo import _api_key, _search_tmdb_id
    tmdb_id = tmdb_id or _search_tmdb_id(media_type, title, year)
    if not tmdb_id:
        return ''
    endpoint = '{}/{}'.format('tv' if media_type == 'tv' else 'movie', tmdb_id)

    def fetch():
        response = requests.get('https://api.themoviedb.org/3/' + endpoint,
                                params={'api_key': _api_key()}, timeout=5)
        response.raise_for_status()
        data = response.json()
        return {'original': data.get('original_name') or data.get('original_title') or ''}

    return (TMDbCache.get_or_fetch(endpoint, {'kind': 'original_title'}, fetch, CACHE_SECONDS) or {}).get('original', '')


def original_title(media_type, title, year='', tmdb_id=None):
    """'' when unknown or the same as the title. media_type: 'tv' or 'movie'."""
    if not title:
        return ''
    try:
        original = _from_library(media_type, title, year) or _from_tmdb(media_type, tmdb_id, title, year)
    except Exception as exc:
        xbmc.log('[plugin.video.milionar] original_title failed for {}: {}'.format(title, exc), xbmc.LOGWARNING)
        return ''
    return original if original and original.strip().lower() != title.strip().lower() else ''
