# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify
import aiohttp
import asyncio
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from urllib.parse import urlparse

app = Flask(__name__)
ua = UserAgent()

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

async def fetch(session, url):
    headers = {'User-Agent': ua.random}
    async with session.get(url, headers=headers) as response:
        return await response.text() if response.status == 200 else None

async def get_download_link(session, episode_url):
    html = await fetch(session, episode_url)
    if not html:
        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:
        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:
        return None
    
    soup = BeautifulSoup(html, 'html.parser')
    final_link_element = soup.select_one("div.btn-loader a")
    return final_link_element.get("href") if final_link_element else None

async def get_episode_data(series_url):
    async with aiohttp.ClientSession() 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')
        episodes = []
        episode_elements = soup.select("#series-episodes > div.widget-body > div > div")
        
        tasks = []
        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(session, episode_url))
            episodes.append({
                "Episoade_Name": f"الحلقة {episoade_order}",
                "episoade_order": episoade_order,
                "url": None
            })
        
        results = await asyncio.gather(*tasks)
        for i, result in enumerate(results):
            episodes[i]["url"] = result if result else "Not Found"
        
        # ترتيب الحلقات من الحلقة الأولى إلى الأخيرة
        episodes.sort(key=lambda x: x["episoade_order"])
        
        return {"episodes": episodes, "success": True}

async def get_movie_data(movie_url):
    async with aiohttp.ClientSession() 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()
        
        # البحث بالمحدد الأساسي أولاً (#tab-5)
        download_link_element = soup.select_one("#tab-5 > div > div > div:nth-child(2) > a")
        
        # إذا لم يتم العثور، جرب المحدد البديل (#tab-4)
        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 in both selectors"}
        
        download_page_url = download_link_element.get("href")
        html = await fetch(session, download_page_url)
        if not html:
            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")
        html = await fetch(session, redirect_url)
        if not html:
            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")
        
        # استخراج اسم السيرفر من الرابط النهائي
        parsed_url = urlparse(final_download_url)
        server_name = parsed_url.netloc
        
        return {
            "movie": {
                "Movie_Name": movie_name,
                "url": final_download_url
            },
            "success": True
        }

@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=True)