# -*- coding: utf-8 -*-
# plugin.video.alkoflix
# resources/lib/indexers/fanarttv_api.py
# © Les alKODIques

import requests
from urllib.parse import urlsplit, urlunsplit, quote
# from modules.kodi_utils import logger

# Clé API publique offerte par Les alKODIques.
API_KEY = '30006d06f4d124007f5de4f568bd7bca'
base_url = 'https://webservice.fanart.tv/v3.2/%s/%s'
default_fanart_meta = {'poster2': '', 'poster2_text': '', 'fanart2': '', 'banner': '', 'clearart': '', 'clearlogo': '', 'landscape': '', 'landscape_text': '', 'discart': '', 'season_posters': {}, 'season_posters_text': {}, 'season_landscapes': {}, 'season_landscapes_text': {}, 'fanart_added': True}
default_fanart_nometa = {'poster2': '', 'poster2_text': '', 'fanart2': '', 'banner': '', 'clearart': '', 'clearlogo': '', 'landscape': '', 'landscape_text': '', 'discart': '', 'season_posters': {}, 'season_posters_text': {}, 'season_landscapes': {}, 'season_landscapes_text': {}, 'fanart_added': False}
timeout = 3.05
session = requests.Session()
session.mount('https://webservice.fanart.tv', requests.adapters.HTTPAdapter(pool_maxsize=100))

# Nettoie et encode une URL d’image pour éviter les erreurs Kodi.
def clean_art_url(url):
	if not url or 'http' not in url:
		return ''
	try:
		parts = urlsplit(url)
		path = quote(parts.path, safe='/%._-~')
		query = quote(parts.query, safe='=&%._-~')
		return urlunsplit((parts.scheme, parts.netloc, path, query, parts.fragment))
	except:
		return url

# Récupère les visuels Fanart.tv d’un média selon la langue demandée.
def get(media_type, language, media_id, client_key, original_language=''):
	if not media_id:
		return default_fanart_meta

	query = base_url % (media_type, media_id)

	headers = {'api-key': API_KEY}
	if client_key:
		headers['client-key'] = client_key

	try:
		response = session.get(query, headers=headers, timeout=timeout)
		response.raise_for_status()
		art = response.json()
	except:
		return default_fanart_meta

	if not isinstance(art, dict):
		return default_fanart_meta

	if art.get('status') == 'error' or 'error message' in art or 'error_message' in art:
		return default_fanart_meta

	art_get = art.get
	if media_type == 'movies':
		fanart_data = {
			'poster2': parse_art(art_get('movieposter'), language, original_language=original_language),
			'poster2_text': parse_art(art_get('movieposter'), language, original_language=original_language, allow_neutral=False),
			'fanart2': parse_art(art_get('moviebackground'), language, prefer_neutral=True, original_language=original_language),
			'banner': parse_art(art_get('moviebanner'), language, original_language=original_language),
			'clearart': parse_art(art_get('movieart', []) + art_get('hdmovieclearart', []), language, original_language=original_language),
			'clearlogo': parse_art(art_get('movielogo', []) + art_get('hdmovielogo', []), language, original_language=original_language),
			'landscape': parse_art(art_get('moviethumb'), language, original_language=original_language),
			'landscape_text': parse_art(art_get('moviethumb'), language, original_language=original_language, allow_neutral=False),
			'discart': parse_art(art_get('moviedisc'), language, original_language=original_language),
			'fanart_added': True
		}
	else:
		fanart_data = {
			'poster2': parse_art(art_get('tvposter'), language, original_language=original_language),
			'poster2_text': parse_art(art_get('tvposter'), language, original_language=original_language, allow_neutral=False),
			'fanart2': parse_art(art_get('showbackground'), language, prefer_neutral=True, original_language=original_language),
			'banner': parse_art(art_get('tvbanner'), language, original_language=original_language),
			'clearart': parse_art(art_get('clearart', []) + art_get('hdclearart', []), language, original_language=original_language),
			'clearlogo': parse_art(art_get('hdtvlogo', []) + art_get('clearlogo', []), language, original_language=original_language),
			'landscape': parse_art(art_get('tvthumb'), language, original_language=original_language),
			'landscape_text': parse_art(art_get('tvthumb'), language, original_language=original_language, allow_neutral=False),
			'season_posters': parse_season_art(art_get('seasonposter', []) + art_get('tvseasonposter', []), language, original_language=original_language),
			'season_posters_text': parse_season_art(art_get('seasonposter', []) + art_get('tvseasonposter', []), language, original_language=original_language, allow_neutral=False),
			'season_landscapes': parse_season_art(art_get('seasonthumb', []) + art_get('tvseasonthumb', []), language, original_language=original_language),
			'season_landscapes_text': parse_season_art(art_get('seasonthumb', []) + art_get('tvseasonthumb', []), language, original_language=original_language, allow_neutral=False),
			'discart': '',
			'fanart_added': True
		}
	return fanart_data

def _normalize_art_language(language):
	language = str(language or '').lower()
	if language.startswith('en'):
		return 'en'
	return 'fr'

# Sélectionne l’image la plus pertinente selon la langue prioritaire demandée.
def parse_art(art, language, prefer_neutral=False, original_language='', season=None, allow_neutral=True):
	if art is None:
		return ''

	try:
		primary = _normalize_art_language(language)
		fallback = 'en' if primary == 'fr' else 'fr'
		neutral_languages = ('00', '', None)
		original_language = str(original_language or '').lower().strip()
		lang_order = []
		if prefer_neutral:
			lang_order.extend(neutral_languages)
			lang_order.extend((primary, fallback))
			if original_language and original_language not in lang_order and original_language not in neutral_languages:
				lang_order.append(original_language)
		else:
			lang_order.extend((primary, fallback))
			# Si FR et EN sont absents, on essaie la VO avant le visuel neutre.
			if original_language and original_language not in lang_order and original_language not in neutral_languages:
				lang_order.append(original_language)
			if allow_neutral:
				lang_order.extend(neutral_languages)
		result = []

		if season is not None:
			season = str(season)
			art = [x for x in art if str(x.get('season', '')) == season]

		for lang in lang_order:
			result = [(x['url'], x.get('likes', 0)) for x in art if x.get('lang') == lang]
			if result:
				break

		if result:
			result.sort(key=lambda x: int(x[1]), reverse=True)
			result = result[0][0]
		else:
			result = ''
	except:
		result = ''

	if 'http' not in result:
		result = ''

	return clean_art_url(result)


# Sélectionne les visuels Fanart.tv propres à chaque saison.
def parse_season_art(art, language, original_language='', allow_neutral=True):
	if not art:
		return {}
	result = {}
	try:
		seasons = []
		for item in art:
			season = item.get('season')
			if season is None or season == '':
				continue
			season = str(season)
			if season not in seasons:
				seasons.append(season)
		for season in seasons:
			url = parse_art(art, language, original_language=original_language, season=season, allow_neutral=allow_neutral)
			if url:
				result[season] = url
	except:
		result = {}
	return result

# Ajoute les visuels Fanart.tv aux métadonnées du média.
def add(media_type, language, media_id, client_key, meta, original_language=''):
	if not media_id:
		meta.update(default_fanart_meta)
	else:
		try:
			meta.update(get(media_type, language, media_id, client_key, original_language))
		except:
			meta.update(default_fanart_meta)
	return meta
