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

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://web.cimafree.vip"
SEARCH_BASE = "https://sei.cimafree.vip"

@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:
            full_title = link['title']

            episode_name_match = re.search(r'(الحلقة \d+)', full_title)
            if not episode_name_match:
                continue
            episode_name = episode_name_match.group(1)

            episode_number_match = re.search(r'الحلقة (\d+)', full_title)
            episode_number = int(episode_number_match.group(1))

            episode_url = BASE_URL + '/' + link['href']

            episode_servers_url = episode_url.replace("watch.php", "play.php")
            server_response = session.get(episode_servers_url)
            if server_response.status_code != 200:
                continue

            server_soup = BeautifulSoup(server_response.text, 'html.parser')
            server_ul = server_soup.find('ul', class_='WatchList')
            if not server_ul:
                continue

            preferred_server = None
            fallback_server = None

            servers = server_ul.find_all('li')
            for server in servers:
                if not server.has_attr('data-embed-url'):
                    continue

                embed_url = server['data-embed-url']
                if "filehd.cc" in embed_url:
                    preferred_server = embed_url.replace("embed-", "")
                    break
                elif "lulu.st" in embed_url and not fallback_server:
                    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_name,
                    "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


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

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

        watch_soup = BeautifulSoup(watch_response.text, 'html.parser')

        movie_name = None
        title_tag = watch_soup.find('title')
        if title_tag:
            raw_title = title_tag.text.strip()
            movie_name = raw_title
            movie_name = re.sub(r'(?i)^مشاهدة\s+فيلم\s*', '', movie_name)
            movie_name = re.sub(r'\s*(كامل|اون\s*لاين|مترجم|HD|اونلاين)\s*', ' ', movie_name)
            movie_name = re.sub(r'\s+', ' ', movie_name).strip()
            movie_name = f"HD فيلم {movie_name}"

        if not movie_name:
            h1_tag = watch_soup.find('h1')
            if h1_tag:
                movie_name = h1_tag.text.strip()
            else:
                movie_name = "فيلم غير معروف"

        movie_play_url = movie_url.replace("watch.php", "play.php")
        play_response = session.get(movie_play_url)
        if play_response.status_code != 200:
            return jsonify({"success": False, "message": "فشل في جلب صفحة التشغيل"}), 400

        play_soup = BeautifulSoup(play_response.text, 'html.parser')
        server_ul = play_soup.find('ul', class_='WatchList')
        if not server_ul:
            return jsonify({"success": False, "message": "لم يتم العثور على السيرفرات"}), 400

        preferred_server = None
        fallback_server = None

        servers = server_ul.find_all('li')
        for server in servers:
            if not server.has_attr('data-embed-url'):
                continue

            embed_url = server['data-embed-url']
            if "filehd.cc" in embed_url:
                preferred_server = embed_url.replace("embed-", "")
                break
            elif "lulu.st" in embed_url and not fallback_server:
                fallback_server = embed_url

        final_url = preferred_server if preferred_server else fallback_server
        if not final_url:
            return jsonify({"success": False, "message": "لم يتم العثور على رابط تشغيل صالح"}), 400

        return jsonify({
            "movie": {
                "Movie_Name": movie_name,
                "url": final_url
            },
            "success": True
        }), 200

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


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

        search_url = f"{SEARCH_BASE}/search.php?keywords={urllib.parse.quote(series_name)}"
        response = session.get(search_url)
        if response.status_code != 200:
            return jsonify({"success": False, "message": "فشل في جلب نتائج البحث"}), 400

        soup = BeautifulSoup(response.text, 'html.parser')
        results_list = soup.find('ul', id='pm-grid')
        if not results_list:
            return jsonify({"success": False, "message": "تعذر العثور على نتائج"}), 404

        episodes_data = []
        links = results_list.find_all('a', href=True, title=True)
        seen_titles = set()

        for a in links:
            title = a['title']
            url = a['href']

            if title in seen_titles:
                continue
            seen_titles.add(title)

            match = re.search(r'الحلقة (\d+)', title)
            if not match:
                continue

            ep_number = int(match.group(1))
            ep_name = f"الحلقة {ep_number}"
            watch_url = url if url.startswith("http") else f"{SEARCH_BASE}/{url}"
            play_url = watch_url.replace("watch.php", "play.php")

            play_res = session.get(play_url)
            if play_res.status_code != 200:
                continue

            play_soup = BeautifulSoup(play_res.text, 'html.parser')
            server_ul = play_soup.find('ul', class_='WatchList')
            if not server_ul:
                continue

            preferred = None
            fallback = None

            for li in server_ul.find_all('li'):
                embed = li.get('data-embed-url')
                if not embed:
                    continue
                if "filehd.cc" in embed:
                    preferred = embed.replace("embed-", "")
                    break
                elif "lulu.st" in embed and not fallback:
                    fallback = embed

            final_url = preferred or fallback
            if not final_url:
                continue

            episodes_data.append({
                "Episoade_Name": ep_name,
                "episoade_order": ep_number,
                "url": final_url
            })

        if not episodes_data:
            return jsonify({"success": False, "message": "لم يتم العثور على حلقات"}), 404

        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)
