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

from urllib.parse import urlparse

from magneto.hosters.common import BaseHosterSource, clean_text, normalize_text, request_json, title_variants


class source(BaseHosterSource):
	provider_key = 'movix'
	provider_name = 'Movix'
	base_setting = 'hoster.movix.url'
	default_base_url = 'https://movix.cloud'
	priority = 5

	def api_base(self):
		base = self.base_url()
		if not base: return ''
		parsed = urlparse(base)
		host = parsed.netloc or parsed.path
		scheme = parsed.scheme or 'https'
		if host.startswith('api.'): return '%s://%s' % (scheme, host)
		return '%s://api.%s' % (scheme, host)

	def headers(self):
		base = self.base_url()
		return {'Origin': base, 'Referer': '%s/' % base} if base else {}

	def _search_content(self, data):
		api = self.api_base()
		if not api: return None
		imdb = data.get('imdb') or ''
		year = str(data.get('year') or '')
		target_titles = [normalize_text(i) for i in title_variants(data, limit=4)]
		for title in title_variants(data, limit=4):
			payload = request_json('%s/api/search' % api, params={'title': title}, headers=self.headers(), timeout=self.timeout)
			results = payload.get('results', []) if isinstance(payload, dict) else []
			for result in results:
				try:
					if imdb and result.get('imdb_id') == imdb: return result
					name = normalize_text(result.get('name') or result.get('title'))
					if name in target_titles and (not year or not result.get('year') or str(result.get('year')) == year): return result
				except: pass
		return None

	def _decode_link(self, link_id):
		if not link_id: return ''
		payload = request_json('%s/api/darkiworld/decode/%s' % (self.api_base(), link_id), headers=self.headers(), timeout=self.timeout)
		if not isinstance(payload, dict) or not payload.get('success'): return ''
		embed = payload.get('embed_url') or {}
		return embed.get('lien') if isinstance(embed, dict) else ''

	def search(self, data):
		content = self._search_content(data)
		if not content: return []
		title_id = content.get('id')
		if not title_id: return []
		is_series = bool(data.get('tvshowtitle'))
		api_type = 'tv' if is_series else 'movie'
		params = {}
		if is_series: params.update({'season': data.get('season'), 'episode': data.get('episode')})
		payload = request_json('%s/api/darkiworld/download/%s/%s' % (self.api_base(), api_type, title_id), params=params, headers=self.headers(), timeout=self.timeout)
		if not isinstance(payload, dict) or not payload.get('success'): return []
		links = payload.get('all') or payload.get('links') or []
		content_title = clean_text(content.get('name') or data.get('tvshowtitle') or data.get('title'))
		results = []
		for link in links:
			try:
				if is_series and link.get('full_saison'): continue
				url = self._decode_link(link.get('id')) or link.get('url') or link.get('link') or ''
				if not url: continue
				quality = link.get('quality') or ''
				language = link.get('language') or ''
				name = '%s %s %s' % (content_title, quality, language)
				if is_series: name = '%s S%02dE%02d %s %s' % (content_title, int(data.get('season') or 0), int(data.get('episode') or 0), quality, language)
				results.append({'link': url, 'hoster': link.get('host_name'), 'quality': quality, 'language': language, 'raw_language': language, 'size': link.get('size'), 'display_name': name})
			except: pass
		return results
