from flask import Flask, request, jsonify
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import re
from urllib.parse import quote

app = Flask(__name__)

# توليد User-Agent عشوائي
ua = UserAgent()
user_agent = ua.random

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


@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 = []

        all_links = soup.find_all("a", href=True)
        for link in all_links:
            episode_title_element = link.select_one("episodetitle")
            if not episode_title_element:
                continue

            episode_text = episode_title_element.get_text(strip=True)
            episode_number_match = re.search(r'(\d+)', episode_text)
            if not episode_number_match:
                continue

            episode_number = int(episode_number_match.group(1))
            episode_url = link["href"]

            episodes_data.append({
                "Episoade_Name": f"الحلقة {episode_number}",
                "episoade_order": episode_number,
                "url": episode_url.strip()
            })

        episodes_data.sort(key=lambda x: x["episoade_order"])

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


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

        encoded_name = quote(name)
        search_url = f"https://wecima.video/?s={encoded_name}"

        search_response = session.get(search_url)
        if search_response.status_code != 200:
            return jsonify({"success": False, "message": "فشل في جلب نتائج البحث"}), 400

        search_soup = BeautifulSoup(search_response.text, 'html.parser')

        # 🔍 جلب أول رابط يحتوي على مسلسل في نتائج البحث
        first_result = None
        for a_tag in search_soup.find_all("a", href=True):
            href = a_tag["href"]
            if "/مسلسل-" in href or "/series/" in href:
                first_result = a_tag
                break

        if not first_result:
            return jsonify({"success": False, "message": "لم يتم العثور على نتائج"}), 404

        series_url = first_result['href']

        # إعادة استخدام نفس منطق جلب الحلقات
        response = session.get(series_url)
        if response.status_code != 200:
            return jsonify({"success": False, "message": "فشل في جلب صفحة المسلسل"}), 400

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

        all_links = soup.find_all("a", href=True)
        for link in all_links:
            episode_title_element = link.select_one("episodetitle")
            if not episode_title_element:
                continue

            episode_text = episode_title_element.get_text(strip=True)
            episode_number_match = re.search(r'(\d+)', episode_text)
            if not episode_number_match:
                continue

            episode_number = int(episode_number_match.group(1))
            episode_url = link["href"]

            episodes_data.append({
                "Episoade_Name": f"الحلقة {episode_number}",
                "episoade_order": episode_number,
                "url": episode_url.strip()
            })

        episodes_data.sort(key=lambda x: x["episoade_order"])

        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)
