from flask import Flask, request, jsonify
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import re 

app = Flask(__name__)

# توليد User-Agent مزيفة
ua = UserAgent()
user_agent = ua.random

# إنشاء جلسة Requests
session = requests.Session()
session.headers.update({'User-Agent': user_agent})

BASE_URL = "https://dal.ahwaktv.net"

@app.route('/api/series', methods=['GET'])
def fetch_series_data():
    try:
        series_url = request.args.get('series_url')
        if not series_url:
            return jsonify({"success": False, "message": "يرجى تقديم رابط المسلسل في معلمة series_url"}), 400

        response = session.get(series_url)
        if response.status_code != 200:
            return jsonify({"success": False, "message": "فشل في جلب صفحة الويب"}), 400

        soup = BeautifulSoup(response.text, 'html.parser')
        episodes_data = []

        episodes_list = soup.find('ul', class_='s')
        if not episodes_list:
            return jsonify({"success": False, "message": "لم يتم العثور على قائمة الحلقات"}), 400

        episode_links = episodes_list.find_all('a')
        
        last_episode_url = None  # لتخزين رابط الحلقة السابقة

        for link in episode_links:
            episode_title = link['title']
            episode_url = BASE_URL + '/' + link['href']
            
            episode_number_match = re.search(r'الحلقة (\d+)', episode_title)
            if not episode_number_match:
                continue
            episode_number = int(episode_number_match.group(1))
            
            # تعديل الرابط للحصول على السيرفرات
            episode_servers_url = episode_url.replace("watch.php", "see.php")
            server_response = session.get(episode_servers_url)
            if server_response.status_code != 200:
                continue
            
            server_soup = BeautifulSoup(server_response.text, 'html.parser')
            server_div = server_soup.find('div', id='pm-servers')
            if not server_div:
                continue
            
            preferred_server = None
            fallback_server = None
            
            servers = server_div.find_all('li')
            for server in servers:
                embed_url = server['data-embed-url']
                if "hlswish.com" in embed_url:
                    preferred_server = embed_url
                    break
                elif "vidhideplus.com" in embed_url:
                    fallback_server = embed_url
            
            final_url = preferred_server if preferred_server else fallback_server

            # **تخطي الحلقة إذا كان رابطها مكررًا**
            if final_url == last_episode_url:
                continue  

            last_episode_url = final_url  # تحديث الرابط الأخير
            
            if final_url:
                episodes_data.append({
                    "Episoade_Name": episode_title,
                    "episoade_order": episode_number,
                    "url": final_url
                })
        
        return jsonify({"success": True, "episodes": episodes_data}), 200

    except Exception as e:
        return jsonify({"success": False, "message": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)
