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

import re
from urllib.parse import quote

from magneto.hosters.common import (
	BaseHosterSource, abs_url, clean_text, html_links, normalize_text, normalize_quality,
	language_code, request_text, title_variants, extract_attr
)


class source(BaseHosterSource):
	provider_key = 'free_telecharger'
	provider_name = 'Free-Telecharger'
	base_setting = 'hoster.free_telecharger.url'
	default_base_url = 'https://www.free-telecharger.mom'
	priority = 8

	def _search_content(self, data):
		base = self.base_url()
		if not base: return None
		year = str(data.get('year') or '')
		target_titles = [normalize_text(i) for i in title_variants(data, limit=5)]
		content_type = 'series' if data.get('tvshowtitle') else 'films'
		for title in title_variants(data, limit=4):
			for page in range(1, 4):
				path = '/%s/recherche1/%s.html?rech_fiche=%s&rech_cat=' % (page, page, quote(title.encode('utf-8')) if False else quote(title))
				if year: path += '&rech_annee=%s' % year
				html = request_text('%s%s' % (base, path), timeout=self.timeout)
				if not html: continue
				blocks = re.findall(r'<div\b[^>]*class=["\'][^"\']*container[^"\']*["\'][^>]*>(.*?)</div>\s*</div>', html, re.I | re.S)
				if not blocks: blocks = [html]
				for block in blocks:
					links = html_links(block, r'\.html')
					for link in links:
						text = clean_text(link.get('text'))
						if not text: continue
						clean_title = re.sub(r'\[.*?\]|\(.*?\)', '', text).strip()
						if normalize_text(clean_title) not in target_titles: continue
						if year and year not in clean_text(block): continue
						return {'link': link.get('href'), 'title': text}
		return None

	def _quality_pages(self, first_link):
		base = self.base_url()
		pages, seen = [], set()
		def add(href):
			if href and href not in seen:
				seen.add(href); pages.append(href)
		add(first_link)
		html = request_text(abs_url(first_link, base), timeout=self.timeout)
		for link in html_links(html, r'\.html'):
			href = link.get('href') or ''
			low = href.lower()
			if any(token in low for token in ('films-', 'series-', 'mangas-', 'saison')):
				add(href)
		return pages

	def _extract_links_from_page(self, page_path, data):
		html = request_text(abs_url(page_path, self.base_url()), timeout=self.timeout)
		if not html: return []
		page_text = clean_text(html)
		quality_match = re.search(r'Qualit[ée]\s*:\s*([^\n\r<]+)', page_text, re.I)
		language_match = re.search(r'Langue\s*:\s*([^\n\r<]+)', page_text, re.I)
		size_match = re.search(r'Taille\s*:\s*([^\n\r<]+)', page_text, re.I)
		quality = normalize_quality(quality_match.group(1) if quality_match else page_text)
		language = language_code(language_match.group(1) if language_match else page_text)
		size = size_match.group(1).strip() if size_match else ''
		results = []
		# Liens directs stockés dans des inputs: <input name="lien" value="...">
		for match in re.finditer(r'<input\b([^>]*name=["\']lien["\'][^>]*)>', html, re.I | re.S):
			url = extract_attr(match.group(1), 'value')
			if not url: continue
			start = max(0, match.start() - 700)
			context = clean_text(html[start:match.start()])
			hoster = ''
			episode = ''
			ep_match = re.search(r'[EeÉé]pisode\s*(\d+)', context)
			if ep_match: episode = ep_match.group(1)
			host_match = re.search(r'(1fichier|Rapidgator|Turbobit|Send\.cm|Darkibox|Webshare|Nitroflare|Katfile|Fikper|DDownload|Filejoker|Filemoon|Streamtape)', context, re.I)
			if host_match: hoster = host_match.group(1)
			if data.get('tvshowtitle'):
				if episode and int(episode) != int(data.get('episode') or 0): continue
				name = '%s S%02dE%02d %s %s' % (data.get('tvshowtitle'), int(data.get('season') or 0), int(data.get('episode') or 0), quality, language)
			else:
				name = '%s %s %s %s' % (data.get('title'), data.get('year'), quality, language)
			results.append({'link': url, 'hoster': hoster, 'quality': quality, 'language': language, 'raw_language': language, 'size': size, 'display_name': name})
		return results

	def search(self, data):
		content = self._search_content(data)
		if not content: return []
		results = []
		for page in self._quality_pages(content.get('link')):
			results.extend(self._extract_links_from_page(page, data))
		return results
