from flask import Flask, request, jsonify
import cloudscraper  # مكتبة لتجاوز Cloudflare

app = Flask(__name__)

# بيانات IPTV
USERNAME = "50005000"
PASSWORD = "562611731736"
IPTV_URL = "http://iptvsmarters.ltd/player_api.php"

# 🔵 إنشاء `scraper` لمحاكاة المتصفح وتجاوز الحماية
scraper = cloudscraper.create_scraper()

# 🔵 `Headers` محسّنة لمحاكاة المتصفح
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept": "application/json",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Referer": "http://iptvsmarters.ltd/",
    "Cache-Control": "max-age=0",
    "Accept-Language": "en-US,en;q=0.9"
}

@app.route('/')
def home():
    return "Welcome to **Xonegold Group** 👋 - Contact with me *Team Xonegold Group*"

# 🔵 إرسال الطلب بدون إعادة المحاولة عند `403`
def make_request(url):
    try:
        response = scraper.get(url, headers=HEADERS)
        
        if response.status_code == 200:
            return response
        else:
            print(f"❌ خطأ غير متوقع: {response.status_code}")
            return None
    except Exception as e:
        print(f"🚨 خطأ أثناء الاتصال: {e}")
        return None

# 🔵 جلب `series_id` بناءً على اسم المسلسل
def get_series_id(series_name):
    url = f"{IPTV_URL}?username={USERNAME}&password={PASSWORD}&action=get_series"
    response = make_request(url)

    if not response:
        return None

    try:
        data = response.json()
        for series in data:
            if series["name"] == series_name:
                return series["series_id"]
    except Exception:
        return None

    return None

# 🔵 جلب جميع حلقات المسلسل ورابط تشغيلها
def get_episodes(series_id):
    url = f"{IPTV_URL}?username={USERNAME}&password={PASSWORD}&action=get_series_info&series_id={series_id}"
    response = make_request(url)

    if not response:
        return []

    try:
        data = response.json()
        episodes_list = []
        if "episodes" in data:
            for season, episodes in data["episodes"].items():
                for episode in episodes:
                    episode_data = {
                        "episode_name": episode["title"],
                        "episode_order": episode["episode_num"],
                        "url": f"http://sn-pro.com:80/series/{USERNAME}/{PASSWORD}/{episode['id']}.mp4"
                    }
                    episodes_list.append(episode_data)
        return episodes_list
    except Exception:
        return []

# 🔵 API Endpoint: البحث عن مسلسل
@app.route('/go', methods=['GET'])
def get_media():
    media_name = request.args.get("name")
    
    if not media_name:
        return jsonify({"error": "يرجى تحديد اسم المسلسل"}), 400

    series_id = get_series_id(media_name)
    if not series_id:
        return jsonify({"error": "المسلسل غير موجود أو لا يمكن الوصول إلى السيرفر"}), 404
    
    episodes = get_episodes(series_id)
    return jsonify({"type": "series", "name": media_name, "episodes": episodes})

# تشغيل السيرفر
if __name__ == '__main__':
    app.run(debug=True)