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

import re, requests
from alko import source_utils
from alko.control import setting as getSetting
from modules.source_objects import _is_blocked_file_source


class source:
	timeout = 10
	priority = 1
	pack_capable = False # packs parsed in sources function
	hasMovies = True
	hasEpisodes = True
	def __init__(self):
		self.language = ['en', 'fr']
		# Instance prioritaire : plus stable/performante pour les résultats FR observés.
		# Les autres instances restent en secours si la prioritaire ne retourne rien.
		self.base_links = (
			"https://comet.feels.legal",
			"https://comet.stremio.ru",
			"https://cometfortheweebs.midnightignite.me"
		)
		self.base_link = self.base_links[0]
		self.movieSearch_link = '/stream/movie/%s.json'
		self.tvSearch_link = '/stream/series/%s:%s:%s.json'
		self.min_seeders = 0

	def _get_streams(self, url, log_error=True):
		try:
			response = requests.get(url, timeout=self.timeout)
			response.raise_for_status()
			data = response.json()
		except:
			if log_error: source_utils.scraper_error('COMET')
			return []
		streams = data.get('streams', []) if isinstance(data, dict) else []
		return streams if isinstance(streams, list) else []

	def _get_streams_from_path(self, path):
		try:
			for index, base_link in enumerate(self.base_links):
				streams = self._get_streams('%s%s' % (base_link, path), log_error=(index == len(self.base_links) - 1))
				if streams:
					self.base_link = base_link
					return streams
		except:
			source_utils.scraper_error('COMET')
		return []

	def sources(self, data, hostDict):
		sources = []
		if not data: return sources
		sources_append = sources.append
		try:
			title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
			title = title.replace('&', 'and').replace('Special Victims Unit', 'SVU').replace('/', ' ').replace(':', ' ')
			title = re.sub(r'\s+', ' ', title).strip()
			aliases = data['aliases']
			episode_title = data['title'] if 'tvshowtitle' in data else None
			total_seasons = data['total_seasons'] if 'tvshowtitle' in data else None
			year = data['year']
			imdb = data['imdb']
			if not imdb: return sources
			if 'tvshowtitle' in data:
				season = data['season']
				episode = data['episode']
				hdlr = 'S%02dE%02d' % (int(season), int(episode))
				path = self.tvSearch_link % (imdb, season, episode)
			else:
				season = episode = None
				hdlr = year
				path = self.movieSearch_link % imdb
			if 'timeout' in data: self.timeout = max(10, int(data['timeout']))
			files = self._get_streams_from_path(path)
			if not files: return sources
			_INFO = re.compile(r'💾.*')
			check_foreign_audio = source_utils.check_foreign_audio()
		except:
			source_utils.scraper_error('COMET')
			return sources

		for file in files:
			try:
				# Sécurité : Comet peut parfois retourner un torrent dont le nom réel
				# est caché dans title/name/behaviorHints.filename. On bloque avant
				# toute création de magnet afin qu'AllDebrid ne voie jamais ce .exe.
				if _is_blocked_file_source(file): continue
				package, episode_start = None, 0
				hash = file.get('infoHash')
				description = file.get('description') or file.get('title') or file.get('name') or ''
				if not hash or not description: continue
				file_title = description.split('\n')
				file_info = next((x for x in file_title if _INFO.search(x)), '')

				name = source_utils.clean_name(file_title[0])
				if _is_blocked_file_source({'name': name, 'description': description, 'raw': file}): continue

				if not source_utils.check_title(title, aliases, name, hdlr, year):
					if total_seasons is None: continue
					valid, last_season = source_utils.filter_show_pack(title, aliases, imdb, year, season, name, total_seasons)
					if not valid:
						valid, episode_start, episode_end = source_utils.filter_season_pack(title, aliases, year, season, name)
						if not valid: continue
						else: package = 'season'
					else: package = 'show'
				name_info = source_utils.info_from_name(name, title, year, hdlr, episode_title)
				if source_utils.remove_lang(name_info, check_foreign_audio): continue
				language = source_utils.release_language(name_info)

				url = 'magnet:?xt=urn:btih:%s&dn=%s' % (hash, name)
				if _is_blocked_file_source({'name': name, 'url': url, 'raw': file}): continue

				try:
					seeders = int(re.search(r'👤\s*(\d+)', file_info).group(1))
					if self.min_seeders > seeders: continue
				except: seeders = 0

				quality, info = source_utils.get_release_quality(name_info, url)
				try:
					size = re.search(r'((?:\d+\,\d+\.\d+|\d+\.\d+|\d+\,\d+|\d+)\s*(?:GB|GiB|Gb|MB|MiB|Mb))', file_info).group(0)
					dsize, isize = source_utils._size(size)
					info.insert(0, isize)
				except: dsize = 0
				info = ' | '.join(info)

				item = {
					'source': 'torrent', 'language': language, 'direct': False, 'debridonly': True,
					'provider': 'comet', 'hash': hash, 'url': url, 'name': name, 'name_info': name_info,
					'quality': quality, 'info': info, 'size': dsize, 'seeders': seeders
				}
				if package: item.update({'package': package, 'true_size': True})
				if package == 'show': item.update({'last_season': last_season})
				if episode_start: item.update({'episode_start': episode_start, 'episode_end': episode_end}) # for partial season packs
				sources_append(item)
			except:
				source_utils.scraper_error('COMET')
		try:
			def _release_text(item):
				return ' '.join(str(item.get(k) or '') for k in ('name_info', 'name', 'info')).lower()

			def _priority(item):
				text = _release_text(item)
				if str(item.get('language') or '').lower() == 'fr': return 0
				if re.search(r'(^|[^a-z0-9])(vostfr|vo\.?stfr|subfrench|french\.?sub|fr\.?sub)([^a-z0-9]|$)', text, re.I): return 1
				return 2

			sources.sort(key=lambda i: (
				_priority(i),
				-int(i.get('seeders', 0) or 0)
			))
		except:
			pass
		return sources
