# -*- coding: utf-8 -*-
"""Title logos (TMDb /images) for series and movies, with tmdb_id resolution.

Dialogs reached from the Kodi library often have no tmdb_id, so the id is
resolved from the library's uniqueid first and from a TMDb search second.
Results (including "no logo") are cached in the TMDb cache for a week.
"""

import json

import requests
import xbmc

from wcs.metadata import TMDbCache

IMAGE_BASE = 'https://image.tmdb.org/t/p/w500'
CACHE_SECONDS = 7 * 24 * 3600


def _api_key():
    from wcs.metadata.TMDbClient import get_tmdb_api_key
    return get_tmdb_api_key()


def pick_logo(logos):
    """Best logo dict: Czech > English > textless > any other language; wide preferred; no SVG."""
    best, best_score = None, -1
    for logo in logos or []:
        path = logo.get('file_path', '') or ''
        if not path or path.lower().endswith('.svg'):
            continue  # Kodi cannot render SVG
        width, height = logo.get('width', 0) or 0, logo.get('height', 0) or 0
        ratio = width / height if height else 0
        lang = logo.get('iso_639_1')
        lang_score = {'cs': 10000, 'en': 5000, None: 3000}.get(lang, 0)
        score = lang_score + (1000 if ratio > 2.0 else 0) + (logo.get('vote_average', 0) or 0)
        if score > best_score:
            best, best_score = logo, score
    return best


def get_logo(tmdb_id, media_type='tv'):
    """Return {'url', 'aspect'} for the title's best logo, or None."""
    if not tmdb_id:
        return None
    endpoint = '{}/{}/images'.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()
        logo = pick_logo(response.json().get('logos', []))
        if not logo:
            return {'url': ''}
        height = logo.get('height') or 1
        return {'url': IMAGE_BASE + logo['file_path'], 'aspect': (logo.get('width') or 0) / float(height)}

    try:
        data = TMDbCache.get_or_fetch(endpoint, {'kind': 'logo'}, fetch, CACHE_SECONDS)
    except Exception as exc:
        xbmc.log('[plugin.video.milionar] TMDbLogo: {} failed: {}'.format(endpoint, exc), xbmc.LOGWARNING)
        return None
    return data if data and data.get('url') else None


def _library_tmdb_id(media_type, title, year=''):
    """tmdb uniqueid of a title in the Kodi video library (exact title match)."""
    if not title:
        return None
    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': ['uniqueid', '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 None
    for item in items:
        if year and str(item.get('year', '')) not in ('', '0', str(year)):
            continue
        tmdb_id = (item.get('uniqueid') or {}).get('tmdb')
        if tmdb_id:
            return tmdb_id
    return None


def _search_tmdb_id(media_type, title, year=''):
    """First TMDb search hit for the title (and year when known)."""
    if not title:
        return None
    endpoint = 'search/{}'.format('tv' if media_type == 'tv' else 'movie')
    params = {'query': title, 'language': 'cs-CZ'}
    if year:
        params['first_air_date_year' if media_type == 'tv' else 'year'] = str(year)[:4]

    def fetch():
        response = requests.get('https://api.themoviedb.org/3/' + endpoint,
                                params=dict(params, api_key=_api_key()), timeout=5)
        response.raise_for_status()
        results = response.json().get('results', [])
        return {'id': results[0].get('id') if results else None}

    try:
        return TMDbCache.get_or_fetch(endpoint, params, fetch, CACHE_SECONDS).get('id')
    except Exception as exc:
        xbmc.log('[plugin.video.milionar] TMDbLogo: search failed for {}: {}'.format(title, exc), xbmc.LOGWARNING)
        return None


def resolve_logo(media_type, tmdb_id=None, title='', year=''):
    """Logo for a series ('tv') or movie ('movie'); resolves a missing tmdb_id first."""
    tmdb_id = tmdb_id or _library_tmdb_id(media_type, title, year) or _search_tmdb_id(media_type, title, year)
    return get_logo(tmdb_id, media_type)
