# created for Fenomscrapers
"""
	Fenomscrapers Project
"""

from json import loads as jsloads
import re, queue
from gearsscrapers.modules import client
from gearsscrapers.modules import source_utils
from gearsscrapers.modules.control import setting as getSetting


class source:
	timeout = 10
	priority = 1
	pack_capable = True
	hasMovies = True
	hasEpisodes = True
	_queue = queue.SimpleQueue()
	def __init__(self):
		self.language = ['en']
		self.base_link = "https://comet.feels.legal"
		self.movieSearch_link = '/stream/movie/%s.json'
		self.tvSearch_link = '/stream/series/%s:%s:%s.json'
		self.min_seeders = 0

	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('/', ' ')
			aliases = data['aliases']
			episode_title = data['title'] if 'tvshowtitle' in data else None
			year = data['year']
			imdb = data['imdb']
			if 'tvshowtitle' in data:
				season = data['season']
				episode = data['episode']
				hdlr = 'S%02dE%02d' % (int(season), int(episode))
				url = '%s/%s%s' % (self.base_link, self._params(), self.tvSearch_link % (imdb, season, episode))
			else:
				hdlr = year
				url = '%s/%s%s' % (self.base_link, self._params(), self.movieSearch_link % imdb)
			# log_utils.log('url = %s' % url)
			try:
				results = client.request(url, timeout=self.timeout)
				files = jsloads(results)['streams']
			except:
				files = []
				raise
			finally:
				self._queue.put_nowait(files) # if seasons
				self._queue.put_nowait(files) # if shows
			_INFO = re.compile(r'💾.*')
			undesirables = source_utils.get_undesirables()
			check_foreign_audio = source_utils.check_foreign_audio()
		except:
			source_utils.scraper_error('COMET')
			return sources

		for file in files:
			try:
				if file.get('url'): hash = re.search(r'\b\w{40}\b', file['url']).group()
				else: hash = file.get('infoHash')
				if not hash: continue
				file_title = file['description'].replace('┈➤', '\n').split('\n')
				_info_lines = [x for x in file_title if _INFO.search(x)]
				file_info = _info_lines[0] if _info_lines else ''

				name = source_utils.clean_name(file_title[0])

				if not source_utils.check_title(title, aliases, name.replace('.(Archie.Bunker', ''), hdlr, year): continue
				name_info = source_utils.info_from_name(name, title, year, hdlr, episode_title)
				if source_utils.remove_lang(name_info, check_foreign_audio): continue
				if undesirables and source_utils.remove_undesirables(name_info, undesirables): continue

				url = 'magnet:?xt=urn:btih:%s&dn=%s' % (hash, name)

				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)

				sources_append({
					'source': 'torrent', 'language': 'en', 'direct': False, 'debridonly': True,
					'provider': 'comet', 'hash': hash, 'url': url, 'name': name, 'name_info': name_info,
					'quality': quality, 'info': info, 'size': dsize, 'seeders': seeders
				})
			except:
				source_utils.scraper_error('COMET')
		return sources

	def sources_packs(self, data, hostDict, search_series=False, total_seasons=None, bypass_filter=False):
		sources = []
		if not data: return sources
		sources_append = sources.append
		try:
			title = data['tvshowtitle'].replace('&', 'and').replace('Special Victims Unit', 'SVU').replace('/', ' ')
			aliases = data['aliases']
			imdb = data['imdb']
			year = data['year']
			season = data['season']
			url = '%s/%s%s' % (self.base_link, self._params(), self.tvSearch_link % (imdb, season, data['episode']))
			files = self._queue.get(timeout=self.timeout + 1)
			_INFO = re.compile(r'💾.*')
			undesirables = source_utils.get_undesirables()
			check_foreign_audio = source_utils.check_foreign_audio()
		except:
			source_utils.scraper_error('COMET')
			return sources

		for file in files:
			try:
				if file.get('url'): hash = re.search(r'\b\w{40}\b', file['url']).group()
				else: hash = file.get('infoHash')
				if not hash: continue
				file_title = file['description'].replace('┈➤', '\n').split('\n')
				_info_lines = [x for x in file_title if _INFO.search(x)]
				file_info = _info_lines[0] if _info_lines else ''

				name = source_utils.clean_name(file_title[0])

				episode_start, episode_end = 0, 0
				if not search_series:
					if not bypass_filter:
						valid, episode_start, episode_end = source_utils.filter_season_pack(title, aliases, year, season, name.replace('.(Archie.Bunker', ''))
						if not valid: continue
					package = 'season'

				elif search_series:
					if not bypass_filter:
						valid, last_season = source_utils.filter_show_pack(title, aliases, imdb, year, season, name.replace('.(Archie.Bunker', ''), total_seasons)
						if not valid: continue
					else: last_season = total_seasons
					package = 'show'

				name_info = source_utils.info_from_name(name, title, year, season=season, pack=package)
				if source_utils.remove_lang(name_info, check_foreign_audio): continue
				if undesirables and source_utils.remove_undesirables(name_info, undesirables): continue

				url = 'magnet:?xt=urn:btih:%s&dn=%s' % (hash, name)
				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': 'en', 'direct': False, 'debridonly': True,
					'provider': 'comet', 'hash': hash, 'url': url, 'name': name, 'name_info': name_info,
					'quality': quality, 'info': info, 'size': dsize, 'seeders': seeders, 'package': package
				}
				if search_series: item.update({'last_season': last_season})
				elif 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')
		return sources

	def _params(self):
		_fallback = (
			'eyJtYXhSZXN1bHRzUGVyUmVzb2x1dGlvbiI6MCwibWF4U2l6ZSI6MCwiY2FjaGVkT25seSI6ZmFsc2Us'
			'InJlbW92ZVRyYXNoIjp0cnVlLCJyZXN1bHRGb3JtYXQiOlsiYWxsIl0sImVuYWJsZVRvcnJlbnQiOnRydWUs'
			'ImRlYnJpZFNlcnZpY2VzIjpbXSwiZGVicmlkU3RyZWFtUHJveHlQYXNzd29yZCI6IiIsImxhbmd1YWdlcyI6'
			'eyJyZXF1aXJlZCI6W10sImV4Y2x1ZGUiOltdLCJwcmVmZXJyZWQiOltdfSwicmVzb2x1dGlvbnMiOnt9LCJv'
			'cHRpb25zIjp7InJlbW92ZV9yYW5rc191bmRlciI6LTEwMDAwMDAwMDAwLCJhbGxvd19lbmdsaXNoX2luX2xhbmd1'
			'YWdlcyI6ZmFsc2UsInJlbW92ZV91bmtub3duX2xhbmd1YWdlcyI6ZmFsc2V9fQ=='
		)
		try:
			import json as _json
			from base64 import b64encode as _b64e
			import xbmcaddon as _xbmcaddon
			_token = _xbmcaddon.Addon('script.module.resolveurl').getSetting('AllDebridResolver_token') or ''
			if _token:
				_cfg = {
					'maxResultsPerResolution': 0, 'maxSize': 0, 'cachedOnly': False,
					'removeTrash': True, 'resultFormat': ['all'],
					'enableTorrent': True,
					'debridServices': [{'service': 'alldebrid', 'apiKey': _token}],
					'debridStreamProxyPassword': '',
					'languages': {'required': [], 'exclude': [], 'preferred': []},
					'resolutions': {},
					'options': {'remove_ranks_under': -10000000000, 'allow_english_in_languages': False, 'remove_unknown_languages': False}
				}
				_b = _b64e(_json.dumps(_cfg, separators=(',', ':')).encode()).decode()
				if '/' not in _b and '+' not in _b:
					return _b
		except Exception:
			pass
		return _fallback
