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

app = Flask(__name__)

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


session = requests.Session()

def fetch_episodes_data(series_url):
    try:
        response = session.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 requests.exceptions.RequestException 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 = session.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 requests.exceptions.RequestException as e:
        print(f"Error: Failed to fetch data from URL {episode_link}. Exception: {e}")
        return None

def fetch_movie_data(movie_url):
    try:
        response = session.get(movie_url)
        response.encoding = 'utf-8'
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # جلب اسم الفيلم
            movie_name_element = soup.select_one('body > div.singlePage > div.singleHeader > div > div > div.col-xl-9.col-lg-9.col-md-9.col-sm-12 > div > div.h1.title')
            movie_name = movie_name_element.text.strip() if movie_name_element else 'Unknown Movie Name'
            
            # تنظيف اسم الفيلم
            movie_name = movie_name.replace('فيلم', '').replace('مترجم', '').strip()
            
            # إزالة تقييم N/A والرموز المرتبطة به
            if "N/A" in movie_name:
                movie_name = movie_name.split("\n")[0].strip()
            
            # جلب رابط المشاهدة
            watch_link_element = soup.select_one('#watchareaa > div > ul > li.active')
            if watch_link_element:
                onclick_attr = watch_link_element.get('onclick', '')
                if 'player_iframe.location.href' in onclick_attr:
                    start_index = onclick_attr.index("'") + 1
                    end_index = onclick_attr.index("'", start_index)
                    watch_link = onclick_attr[start_index:end_index]
                else:
                    watch_link = None
            else:
                watch_link = None
            
            return {
                'movie_name': movie_name,
                'url': watch_link
            }
        else:
            print(f"Error: Received status code {response.status_code} for URL {movie_url}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"Error: Failed to fetch data from URL {movie_url}. Exception: {e}")
        return None


@app.route('/go', methods=['GET'])
def get_media_data():
    series_url = request.args.get('series_url')
    movie_url = request.args.get('movie_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
    elif movie_url:
        movie_data = fetch_movie_data(movie_url)
        if movie_data:
            return jsonify(movie_data), 200
        else:
            return jsonify({"error": "Failed to fetch movie data. Please check the movie URL or try again later."}), 500
    else:
        return jsonify({"error": "No series URL or movie URL provided. Please provide a valid series or movie URL in the query parameter."}), 400

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