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

app = Flask(__name__)

# إنشاء Scraper من cloudscraper لتجاوز Cloudflare
scraper = cloudscraper.create_scraper()

@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 = scraper.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).replace(":443", "")
            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:
            return match_mp4.group(1).replace(":443", "")
        
        return None

    except Exception 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:
        response = scraper.get(series_url)
        response.encoding = 'utf-8'
        soup = BeautifulSoup(response.content, 'html.parser')

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

        episodes.reverse()

        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,
                "url": extract_m3u8_from_network(link)
            })

        return jsonify(episodes_data)

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

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