# -*- coding: utf-8 -*-
# plugin.video.alkoflix
# resources/lib/magneto/tr4ker.py

import re

from modules.private_torznab import PrivateTorznabSource


class source(PrivateTorznabSource):
	provider_key = 'tr4ker'
	provider_name = 'TR4KER'
	api_setting = 'private.tr4ker.api_key'
	base_url = 'https://tr4ker.net/torznab'
	response_mode = 'xml'

	# TR4KER expose une API Torznab compatible Prowlarr. La clé personnelle de
	# l'utilisateur est envoyée comme apikey Torznab, puis en secours via X-Api-Key.
	auth_mode = 'query_apikey'
	auth_modes = ('query_apikey', 'x_api_key')
	try_next_auth_on_empty = True

	# Important : TR4KER doit rester une source privée stricte.
	# On interroge uniquement par identifiants TMDb/IMDb. Aucune recherche texte
	# titre/année ne doit être lancée, afin d'éviter les mauvais matchs.
	trust_api_results = True
	allow_loose_private_match = False

	max_requests_per_minute = 60
	priority = 4

	def _clean_tmdb_id(self, data):
		try:
			value = str((data or {}).get('tmdb') or (data or {}).get('tmdb_id') or '').strip()
			if not value: return ''
			match = re.search(r'(\d+)', value)
			return match.group(1) if match else ''
		except:
			return ''

	def _clean_imdb_id(self, data):
		try:
			value = str((data or {}).get('imdb') or (data or {}).get('imdb_id') or '').strip()
			if not value: return ''
			if value.lower() in ('none', 'null', 'false', '0'): return ''
			match = re.search(r'tt\d+', value, re.I)
			if match: return match.group(0).lower()
			match = re.search(r'\d+', value)
			return 'tt%s' % match.group(0) if match else ''
		except:
			return ''

	def _id_only_params_chain(self, data, search_type, include_episode=False, season_only=False):
		params_list = []
		try:
			base = {'t': search_type}
			if include_episode or season_only:
				season = (data or {}).get('season')
				if season not in ('', None): base['season'] = str(season)
			if include_episode:
				episode = (data or {}).get('episode')
				if episode not in ('', None): base['episode'] = str(episode)

			# TMDb en premier : c'est l'identifiant principal d'alkoFlix.
			tmdb = self._clean_tmdb_id(data)
			if tmdb:
				params = dict(base)
				params['tmdbid'] = tmdb
				self._append_unique_params(params_list, params)

			# IMDb en second : utile si TR4KER/Torznab ne mappe pas encore le TMDb.
			imdb = self._clean_imdb_id(data)
			if imdb:
				params = dict(base)
				params['imdbid'] = imdb
				self._append_unique_params(params_list, params)
		except:
			pass
		return params_list

	def _movie_params(self, data):
		return self._id_only_params_chain(data, 'movie')

	def _episode_params(self, data):
		return self._id_only_params_chain(data, 'tvsearch', include_episode=True)

	def _season_params(self, data):
		return self._id_only_params_chain(data, 'tvsearch', season_only=True)

	def _show_params(self, data):
		return self._id_only_params_chain(data, 'tvsearch')
