# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from six import text_type
from six.moves.urllib.parse import quote
from resources.lib.dns import customdns
from resources.lib.common import make_session, log, DEFAULT_TIMEOUT

customdns()

API_KEY = "92c1507cc18d85290e7a0b96abb37316"
TMDB_BASE_URL = "https://api.themoviedb.org/3"
SESSION = make_session()


def _safe_text(value):
    if value is None:
        return ''
    if isinstance(value, text_type):
        return value
    try:
        return value.decode('utf-8')
    except Exception:
        return text_type(value)


def get_json(url):
    try:
        response = SESSION.get(url, timeout=DEFAULT_TIMEOUT)
        response.encoding = 'utf-8'
        if response.status_code != 200:
            log('TMDB HTTP {} for {}'.format(response.status_code, url), level=2)
            return {}
        data = response.json()
        return data if isinstance(data, dict) else {}
    except Exception as exc:
        log('TMDB request failed: {}'.format(exc), level=4)
        return {}


def _media_kind(type_):
    return 'tv' if type_ == 'series' else 'movie'


def _build_item(item, type_):
    year_key = 'release_date' if type_ == 'movie' else 'first_air_date'
    year = (item.get(year_key) or '')[:4]
    return {
        'id': text_type(item.get('id', '')),
        'title': _safe_text(item.get('title') or item.get('name') or ''),
        'poster': "https://image.tmdb.org/t/p/w500{}".format(item['poster_path']) if item.get('poster_path') else None,
        'background': "https://image.tmdb.org/t/p/original{}".format(item['backdrop_path']) if item.get('backdrop_path') else None,
        'description': _safe_text(item.get('overview', '')),
        'year': year
    }


def get_items(type_, category, page=1):
    media = _media_kind(type_)
    if category == 'trending':
        url = TMDB_BASE_URL + "/trending/{}/week?api_key={}&language=pt-BR&page={}".format(media, API_KEY, page)
    elif category == 'top':
        url = TMDB_BASE_URL + "/{}/top_rated?api_key={}&language=pt-BR&page={}".format(media, API_KEY, page)
    elif category == 'latest':
        endpoint = 'airing_today' if media == 'tv' else 'now_playing'
        url = TMDB_BASE_URL + "/{}/{}?api_key={}&language=pt-BR&page={}".format(media, endpoint, API_KEY, page)
    else:
        url = TMDB_BASE_URL + "/discover/{}?api_key={}&language=pt-BR&page={}".format(media, API_KEY, page)

    data = get_json(url)
    return [_build_item(item, type_) for item in data.get('results', []) if item.get('id')]


def get_meta(type_, tmdb_id):
    media = _media_kind(type_)
    url = TMDB_BASE_URL + "/{}/{}?api_key={}&language=pt-BR".format(media, tmdb_id, API_KEY)
    data = get_json(url)
    year_key = 'first_air_date' if type_ == 'series' else 'release_date'
    year = (data.get(year_key) or '')[:4]
    return {
        'name': _safe_text(data.get('name') if type_ == 'series' else data.get('title')),
        'description': _safe_text(data.get('overview', '')),
        'poster': "https://image.tmdb.org/t/p/w500{}".format(data['poster_path']) if data.get('poster_path') else None,
        'background': "https://image.tmdb.org/t/p/original{}".format(data['backdrop_path']) if data.get('backdrop_path') else None,
        'year': year
    }


def get_seasons(type_, tmdb_id):
    if type_ != 'series':
        return []

    url = TMDB_BASE_URL + "/tv/{}?api_key={}&language=pt-BR".format(tmdb_id, API_KEY)
    data = get_json(url)
    seasons = []
    for season in data.get('seasons', []):
        if season.get('season_number') is None:
            continue
        year = (season.get('air_date') or '')[:4]
        seasons.append({
            'season_number': season['season_number'],
            'name': _safe_text(season.get('name') or 'Temporada {}'.format(season['season_number'])),
            'poster': "https://image.tmdb.org/t/p/w500{}".format(season['poster_path']) if season.get('poster_path') else None,
            'description': _safe_text(season.get('overview', '')),
            'episode_count': season.get('episode_count', 0),
            'year': year
        })
    return seasons


def get_episodes(type_, tmdb_id, season_number):
    if type_ != 'series':
        return []

    url = TMDB_BASE_URL + "/tv/{}/season/{}?api_key={}&language=pt-BR".format(tmdb_id, season_number, API_KEY)
    data = get_json(url)
    episodes = []
    for episode in data.get('episodes', []):
        number = episode.get('episode_number')
        if number is None:
            continue
        year = (episode.get('air_date') or '')[:4]
        episodes.append({
            'episode_number': number,
            'name': _safe_text(episode.get('name') or 'Episódio {}'.format(number)),
            'poster': "https://image.tmdb.org/t/p/w500{}".format(episode['still_path']) if episode.get('still_path') else None,
            'description': _safe_text(episode.get('overview', '')),
            'id': text_type(episode.get('id', '')),
            'year': year
        })
    return episodes


def search(type_, query, page=1):
    query = _safe_text(query).strip()
    if not query:
        return []

    encoded_query = quote(query, safe='')
    media = _media_kind(type_)
    url = TMDB_BASE_URL + "/search/{}?api_key={}&language=pt-BR&query={}&page={}".format(
        media, API_KEY, encoded_query, page
    )
    data = get_json(url)
    return [_build_item(item, type_) for item in data.get('results', []) if item.get('id')]


def get_imdb_id_tmdb(tmdb_id, media_type):
    media = 'tv' if media_type == 'series' else media_type
    url = TMDB_BASE_URL + "/{}/{}/external_ids?api_key={}".format(text_type(media), text_type(tmdb_id), text_type(API_KEY))
    data = get_json(url)
    imdb_id = data.get('imdb_id')
    if not imdb_id:
        log('TMDB external_ids sem imdb_id para {} {}'.format(media, tmdb_id), level=2)
    return imdb_id
