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

app = Flask(__name__)

# Create a cloudscraper session with a custom User-Agent
scraper = cloudscraper.create_scraper(browser={'browser': 'chrome', 'platform': 'windows', 'mobile': False})

def fetch_episodes_data(series_url):
    try:
        response = scraper.get(series_url)
        response.encoding = 'utf-8'
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            episodes_list = soup.select('#streamBox > div.form-row > div:nth-child(2) a')
            
            episodes_data = []
            for episode in episodes_list:
                episode_title = episode.text.strip()
                episode_link = episode['href']
                episode_number = episode_title.split()[-1]  # تحديد رقم الحلقة من النص
                
                # جلب رابط iframe لكل حلقة
                episode_iframe_link = fetch_episode_iframe_link(episode_link)
                
                episodes_data.append({
                    'episode_name': episode_title,
                    'episode_link': episode_link,
                    'episode_order': episode_number,
                    'url': episode_iframe_link
                })
            
            return episodes_data
        else:
            print(f"Error: Received status code {response.status_code} for URL {series_url}")
            return None
    except Exception as e:
        print(f"Error: Failed to fetch data from URL {series_url}. Exception: {e}")
        return None

def fetch_episode_iframe_link(episode_link):
    try:
        response = scraper.get(episode_link)
        response.encoding = 'utf-8'
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            iframe_links = soup.select('#streamBox > div.form-row > div:nth-child(1) ul.tabs-ul li.active')
            
            for link in iframe_links:
                onclick_attr = link.get('onclick', '')
                if 'player_iframe.location.href' in onclick_attr:
                    # استخراج رابط iframe من الـ onclick
                    start_index = onclick_attr.index("'") + 1
                    end_index = onclick_attr.index("'", start_index)
                    iframe_link = onclick_attr[start_index:end_index]
                    return iframe_link
        else:
            print(f"Error: Received status code {response.status_code} for URL {episode_link}")
            return None
    except Exception as e:
        print(f"Error: Failed to fetch data from URL {episode_link}. Exception: {e}")
        return None

@app.route('/go', methods=['GET'])
def get_series_data():
    series_url = request.args.get('series_url')
    if series_url:
        episodes_data = fetch_episodes_data(series_url)
        if episodes_data:
            return jsonify(episodes_data), 200
        else:
            return jsonify({"error": "Failed to fetch episodes data. Please check the series URL or try again later."}), 500
    return jsonify({"error": "No series URL provided. Please provide a valid series URL in the query parameter 'series_url'."}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
