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

app = Flask(__name__)

# تعريف الـ Headers مع User-Agent بدون حروف خاصة
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
}

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

def extract_m3u8_from_network(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
        "Referer": "https://www.farfeshplus.online/"
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # إثارة استثناء لأكواد الحالة السيئة
        content = response.text

        # البحث عن رابط m3u8
        match_m3u8 = re.search(r'(https?://[^\s]+\.m3u8)[^\s]*', content)
        if match_m3u8:
            m3u8_url = match_m3u8.group(1)
            # إزالة :443 من الرابط إذا وجدت
            m3u8_url = m3u8_url.replace(":443", "")
            # إزالة /playlist.m3u8 من نهاية الرابط إذا كان موجودًا
            m3u8_url = re.sub(r'/playlist\.m3u8$', '', m3u8_url)
            return m3u8_url
        
        # البحث عن رابط mp4
        match_mp4 = re.search(r'(https?://[^\s]+\.mp4(?:\?[^\s]*)?)', content)
        if match_mp4:
            mp4_url = match_mp4.group(1)
            # إزالة :443 من الرابط إذا وجدت
            mp4_url = mp4_url.replace(":443", "")
            return mp4_url
        
        return None

    except requests.exceptions.RequestException as e:
        print(f"Error fetching content: {e}")
        return None


@app.route('/go', methods=['GET'])
def get_series_episodes():
    series_url = request.args.get('series_url')
    
    if not series_url:
        return jsonify({'error': 'Missing series_url parameter'}), 400
    
    try:
        # إرسال طلب GET إلى رابط المسلسل
        response = requests.get(series_url, headers=headers)
        response.encoding = 'utf-8'  # لضمان التشفير الصحيح للصفحة
        soup = BeautifulSoup(response.content, 'html.parser')

        episodes_data = []
        episodes = soup.select('table[width="570"] table[width="190"]')

        # جلب الحلقات بالترتيب الصحيح من الأعلى إلى الأسفل
        episodes.reverse()

        episode_counter = 1  # مؤشر ترتيب الحلقة
        
        for episode in episodes:
            link = episode.find('a', class_='opacityit')['href']
            image = episode.find('img')['src']
            title = episode.find('img')['title']
            
            episodes_data.append({
                "episode_name": title,
                "episode_link": link,
                "episode_image": image,
                "episode_order": episode_counter,
                "url": None  # Placeholder for the m3u8 link to be filled later
            })
            
            episode_counter += 1

        # جلب روابط m3u8 لكل حلقة
        for episode in episodes_data:
            link = episode['episode_link']
            m3u8_link = extract_m3u8_from_network(link)
            episode['url'] = m3u8_link

        return jsonify(episodes_data)

    except Exception as e:
        return jsonify({'error': str(e)}), 500

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