# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
import aiohttp
import asyncio
from bs4 import BeautifulSoup
import random
import logging

# إعداد logging لرؤية الأخطاء (اختياري)
logging.basicConfig(level=logging.INFO)

app = Flask(__name__)

USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",
]

def get_random_user_agent():
    return random.choice(USER_AGENTS)

# ✅ timeout موحد (يمكنك تغييره هنا)
DEFAULT_TIMEOUT = 20  # بالثواني
MAX_RETRIES = 2       # عدد محاولات إعادة المحاولة

async def fetch(session, url, timeout=DEFAULT_TIMEOUT):
    headers = {
        'User-Agent': get_random_user_agent(),
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language': 'ar,en-US;q=0.7,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate',
        'DNT': '1',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
    }
    try:
        async with session.get(url, headers=headers, timeout=aiohttp.ClientTimeout(total=timeout)) as response:
            return await response.text() if response.status == 200 else None
    except Exception as e:
        logging.debug(f"Fetch failed for {url}: {e}")
        return None

async def get_download_link_with_retry(session, episode_url, retries=MAX_RETRIES):
    for attempt in range(retries + 1):
        html = await fetch(session, episode_url)
        if not html:
            if attempt < retries:
                await asyncio.sleep(0.5)  # تأخير قصير قبل المحاولة التالية
                continue
            else:
                return None

        soup = BeautifulSoup(html, 'html.parser')
        download_page_link = soup.select_one("#tab-4 > div > div > div:nth-child(2) > a")
        if not download_page_link:
            return None

        download_page_url = download_page_link.get("href")
        html = await fetch(session, download_page_url)
        if not html:
            if attempt < retries:
                await asyncio.sleep(0.5)
                continue
            else:
                return None

        soup = BeautifulSoup(html, 'html.parser')
        redirect_link_element = soup.select_one("body > div.site-container > div > div.content > a:nth-child(2)")
        if not redirect_link_element:
            return None

        redirect_url = redirect_link_element.get("href")
        html = await fetch(session, redirect_url)
        if not html:
            if attempt < retries:
                await asyncio.sleep(0.5)
                continue
            else:
                return None

        soup = BeautifulSoup(html, 'html.parser')
        final_link_element = soup.select_one("div.btn-loader a")
        if final_link_element:
            return final_link_element.get("href")
        else:
            # إذا فشل استخراج الرابط النهائي، لا نعيد محاولة لأن الخطأ منهي
            return None

    return None

async def get_episode_data(series_url):
    connector = aiohttp.TCPConnector(limit=50, limit_per_host=20)
    timeout = aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)

    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
        html = await fetch(session, series_url)
        if not html:
            return {"success": False, "error": "Failed to fetch series page"}

        soup = BeautifulSoup(html, 'html.parser')
        episode_elements = soup.select("#series-episodes > div.widget-body > div > div")
        if not episode_elements:
            return {"success": False, "error": "No episodes found"}

        tasks = []
        episodes_info = []

        for episode in episode_elements:
            title_element = episode.select_one("h2 a")
            if not title_element:
                continue

            episoade_name = title_element.text.strip()
            episode_url = title_element.get("href")
            episoade_order = next((int(word) for word in episoade_name.split() if word.isdigit()), None)

            tasks.append(get_download_link_with_retry(session, episode_url))
            episodes_info.append({
                "Episoade_Name": f"الحلقة {episoade_order}",
                "episoade_order": episoade_order,
            })

        results = await asyncio.gather(*tasks, return_exceptions=True)

        episodes = []
        for i, result in enumerate(results):
            if isinstance(result, Exception):
                url = f"Error: {type(result).__name__}"
            else:
                url = result if result else "Not Found"

            episodes.append({
                "Episoade_Name": episodes_info[i]["Episoade_Name"],
                "episoade_order": episodes_info[i]["episoade_order"],
                "url": url
            })

        episodes = [ep for ep in episodes if ep["episoade_order"] is not None]
        episodes.sort(key=lambda x: x["episoade_order"])

        return {"episodes": episodes, "success": True}

# === get_movie_data مع نفس التحسينات ===
async def get_movie_data(movie_url):
    connector = aiohttp.TCPConnector(limit=10)
    timeout = aiohttp.ClientTimeout(total=DEFAULT_TIMEOUT)
    async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
        html = await fetch(session, movie_url)
        if not html:
            return {"success": False, "error": "Failed to fetch movie page"}

        soup = BeautifulSoup(html, 'html.parser')
        movie_title_element = soup.select_one("body > div.site-container > div.page.page-movie.page-film > div.movie-cover.mb-4.without-cover > div > div > div.col-lg-7.pr-lg-4.col-md-5.col-sm-8.mb-4.mb-sm-0.px-4.px-sm-0 > h1")
        if not movie_title_element:
            return {"success": False, "error": "Movie title not found"}

        movie_name = movie_title_element.text.strip()

        download_link_element = soup.select_one("#tab-5 > div > div > div:nth-child(2) > a")
        if not download_link_element:
            download_link_element = soup.select_one("#tab-4 > div > div > div:nth-child(2) > a")
        if not download_link_element:
            return {"success": False, "error": "Download page link not found"}

        download_page_url = download_link_element.get("href")

        # محاولة جلب صفحة التحميل مع retry
        for attempt in range(MAX_RETRIES + 1):
            html = await fetch(session, download_page_url)
            if html:
                break
            if attempt < MAX_RETRIES:
                await asyncio.sleep(0.5)
        else:
            return {"success": False, "error": "Failed to fetch download page"}

        soup = BeautifulSoup(html, 'html.parser')
        redirect_link_element = soup.select_one("body > div.site-container > div > div.content > a:nth-child(2)")
        if not redirect_link_element:
            return {"success": False, "error": "Redirect link not found"}

        redirect_url = redirect_link_element.get("href")

        for attempt in range(MAX_RETRIES + 1):
            html = await fetch(session, redirect_url)
            if html:
                break
            if attempt < MAX_RETRIES:
                await asyncio.sleep(0.5)
        else:
            return {"success": False, "error": "Failed to fetch final download page"}

        soup = BeautifulSoup(html, 'html.parser')
        final_link_element = soup.select_one("body > div.site-container > div.page-redirect > div > div > div > div.my-5 > div > a")
        if not final_link_element:
            return {"success": False, "error": "Final download link not found"}

        final_download_url = final_link_element.get("href")
        return {
            "movie": {
                "Movie_Name": movie_name,
                "url": final_download_url
            },
            "success": True
        }

@app.route("/")
def home():
    return "Welcome To **xonegold group**‹ - Contact with me *Team xonegold group*"

@app.route("/api/series", methods=["GET"])
def scrape_series():
    series_url = request.args.get("series_url")
    if not series_url:
        return jsonify({"success": False, "error": "Missing series_url parameter"}), 400
    data = asyncio.run(get_episode_data(series_url))
    return jsonify(data)

@app.route("/api/movie", methods=["GET"])
def scrape_movie():
    movie_url = request.args.get("movie_url")
    if not movie_url:
        return jsonify({"success": False, "error": "Missing movie_url parameter"}), 400
    data = asyncio.run(get_movie_data(movie_url))
    return jsonify(data)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=False, threaded=True)