# -*- coding: utf-8 -*-
# plugin.video.alkoflix
# resources/lib/catalogue/french_stream.py

import re


FRENCH_STREAM_MANIFEST_ID = 'community.french-stream-public'


def _text(value):
	try: return str(value or '').strip()
	except: return ''


def _lower(value):
	return _text(value).lower()


def is_manifest(manifest):
	"""Détecte uniquement le manifeste public French Stream ajouté en catalogue personnalisé."""
	if not isinstance(manifest, dict): return False
	manifest_id = _lower(manifest.get('id'))
	manifest_name = _lower(manifest.get('name'))
	if manifest_id == FRENCH_STREAM_MANIFEST_ID: return True
	if 'french stream' in manifest_name: return True
	try:
		prefixes = [_lower(i) for i in manifest.get('idPrefixes', []) or []]
		catalog_ids = [_lower((i or {}).get('id')) for i in manifest.get('catalogs', []) or [] if isinstance(i, dict)]
		return 'fs:' in prefixes and any(i.startswith('fs-') or i == 'fs-search' for i in catalog_ids)
	except:
		return False


def is_catalog(cat):
	if not isinstance(cat, dict): return False
	catalog_id = _lower(cat.get('id'))
	return catalog_id.startswith('fs-') or catalog_id == 'fs-search'


def is_search_catalog(cat):
	if not is_catalog(cat): return False
	if _lower(cat.get('id')) != 'fs-search': return False
	for extra in (cat.get('extra') or []):
		if isinstance(extra, dict) and _lower(extra.get('name')) == 'search' and extra.get('isRequired'):
			return True
	return False


FS_DEFAULT_ICON = 'fresh.png'


def manifest_label(manifest=None):
	if is_manifest(manifest):
		return 'Catalogue'
	return 'Catalogue personnalisé'


def manifest_icon(manifest=None):
	# Icône locale volontaire : les logos distants du manifest peuvent ne pas
	# apparaître correctement dans le menu racine selon le skin/cache Kodi.
	if is_manifest(manifest):
		return FS_DEFAULT_ICON
	return 'folder.png'


def group_icon(group):
	return {
		'movie': 'movies.png',
		'series': 'tv.png',
		'anime': 'anime.png',
		'lists': 'lists.png'
	}.get(_lower(group), 'folder.png')


def _catalog_text(cat):
	return ' %s %s %s ' % (_lower((cat or {}).get('id')), _lower((cat or {}).get('name')), _lower((cat or {}).get('type')))


def icon_for_catalog(cat):
	# Ne jamais décorer les autres manifests personnalisés ici.
	# French Stream est le seul catalogue connu à exposer les dossiers fs-* / fs-search.
	if not is_catalog(cat):
		return 'folder.png'
	catalog_id = _lower((cat or {}).get('id'))
	catalog_type = _lower((cat or {}).get('type'))
	text = _catalog_text(cat)
	if is_search_catalog(cat):
		return 'search_tv.png' if catalog_type in ('series', 'tvshow', 'tvshows') else 'search_movie.png'
	# Entrées récentes / nouveautés
	if 'dernier' in text or 'derniere' in text or 'dernière' in text or 'latest' in text:
		return 'fresh.png'
	# Plateformes / diffuseurs propres à French Stream
	if 'prime' in text or 'amazon' in text:
		return 'amazon.png'
	if 'netflix' in text or 'appletv' in text or 'apple tv' in text or 'disney' in text:
		return 'tv.png'
	# Langues / pays
	if catalog_id.startswith('fs-lang-') or 'pays ' in text:
		return 'languages.png'
	# Tags thématiques
	if catalog_id.startswith('fs-tag-'):
		tag_map = (
			(('alien', 'ai', 'space', 'time-loop', 'time-travel', 'dystopia'), 'genre_scifi.png'),
			(('haunted', 'serial-killer', 'slasher', 'vampire', 'zombie'), 'genre_horror.png'),
			(('love', 'lgbt'), 'genre_romance.png'),
			(('martial-arts', 'superhero'), 'genre_action.png'),
			(('drug', 'heist'), 'genre_crime.png'),
			(('true-story', 'religion'), 'genre_history.png'),
			(('friendship', 'autism', 'coming-of-age'), 'genre_family.png'),
			(('disaster', 'survival', 'revenge'), 'genre_thriller.png'),
		)
		for keys, icon in tag_map:
			if any(key in catalog_id for key in keys):
				return icon
		return 'tag.png'
	# Genres principaux
	genre_map = (
		(('action', 'art-martiaux'), 'genre_action.png'),
		(('aventures', 'adventure'), 'genre_adventure.png'),
		(('animations', 'animation'), 'genre_animation.png'),
		(('comedies', 'comédies', 'comedy'), 'genre_comedy.png'),
		(('policiers', 'espionnages', 'crime'), 'genre_crime.png'),
		(('documentaires', 'documentary'), 'genre_documentary.png'),
		(('drames', 'drama'), 'genre_drama.png'),
		(('familles', 'family'), 'genre_family.png'),
		(('fantastiques', 'fantasy'), 'genre_fantasy.png'),
		(('historiques', 'history'), 'genre_history.png'),
		(('horreur', 'horror'), 'genre_horror.png'),
		(('spectacle', 'music'), 'genre_music.png'),
		(('romances', 'romance'), 'genre_romance.png'),
		(('science-fictions', 'science fiction', 'sci-fi'), 'genre_scifi.png'),
		(('thrillers', 'thriller'), 'genre_thriller.png'),
		(('guerres', 'war'), 'genre_war.png'),
		(('westerns', 'western'), 'genre_western.png'),
		(('biopics', 'biopic'), 'people.png'),
	)
	for keys, icon in genre_map:
		if any(key in text for key in keys):
			return icon
	return 'movies.png' if catalog_type == 'movie' else 'tv.png'


def patch_route_params(cat, params):
	params = dict(params or {})
	if is_search_catalog(cat):
		params['search_required'] = 'true'
		params['iconImage'] = icon_for_catalog(cat)
	return params


def is_fs_id(value):
	return _lower(value).startswith('fs:')


def id_parts(value):
	"""Retourne (tmdb_id, imdb_id) même si l'ID principal reste un ID interne fs:."""
	value = _text(value)
	if not value: return '', ''
	tmdb_id, imdb_id = '', ''
	match = re.search(r'(?:^|[:|/_-])tmdb:?([0-9]+)(?:$|[:|/_-])', value, flags=re.I)
	if match: tmdb_id = match.group(1)
	match = re.search(r'(tt\d+)', value, flags=re.I)
	if match: imdb_id = match.group(1)
	return tmdb_id, imdb_id


def should_use_catalogue_meta_for_series(item, id_type='', media_id=''):
	"""
	French Stream peut fournir un ID fs: en plus d'un IMDb/TMDb.
	Quand un vrai ID média existe, alkoFlix doit garder la navigation native TMDb
	et seulement transporter l'ID fs: comme identifiant de catalogue.
	"""
	if not isinstance(item, dict): return False
	if not is_fs_id(item.get('id')): return False
	return not (id_type and media_id)
