import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

SCRAPERAPI_KEY = '1981a934fe7f91d3872c3730af2b0bf2'
SCRAPERAPI_URL = 'http://api.scraperapi.com'

def create_session_with_retries():
    session = requests.Session()
    retry = Retry(
        total=5,
        backoff_factor=1,
        status_forcelist=[500, 502, 503, 504],
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session

def fetch_url(url):
    session = create_session_with_retries()
    encoded_url = requests.utils.requote_uri(url)
    params = {
        'api_key': SCRAPERAPI_KEY,
        'url': encoded_url
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    try:
        response = session.get(SCRAPERAPI_URL, params=params, headers=headers, verify=False)
        response.raise_for_status()
        return response
    except requests.RequestException as e:
        print(f"Error fetching URL: {e}")
        return None

def get_full_episode_url(session, episode_link):
    try:
        print(f"Fetching full episode URL from: {episode_link}")
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
        }
        response = session.get(episode_link, headers=headers, verify=False)
        response.raise_for_status()
        full_url = response.url
        full_url_with_watch = f"{full_url.rstrip('/')}/watch/"
        print(f"Full episode URL with 'watch/': {full_url_with_watch}")
        return full_url_with_watch
    except requests.RequestException as e:
        print(f"Error getting full episode URL: {e}")
        return None

def get_watch_url(session, episode_link):
    try:
        print(f"Fetching watch URL from: {episode_link}")
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
        }
        response = session.get(episode_link, headers=headers, verify=False)
        response.raise_for_status()
        soup = BeautifulSoup(response.content, 'html.parser')

        watch_list = soup.find('div', class_='watch')
        if not watch_list:
            watch_list = soup.find('ul', class_='server-list')
            if not watch_list:
                print("لم يتم العثور على قائمة السيرفرات.")
                return None

        url = None
        server_items = watch_list.find_all('li')
        for server in server_items:
            server_name = server.get_text(strip=True)
            server_url = server.get('data-watch')

            if "سيرفر شانيل TV" in server_name:
                url = server_url
                break
            elif "hd1.hd-cdn.xyz" in server_name:
                url = server_url.replace("embed-", "")
                break
            elif "strwish" in server_name:
                url = server_url
                break

        print(f"Watch URL: {url}")
        return url
    except requests.RequestException as e:
        print(f"Error getting watch URL: {e}")
        return None

def get_episodes_info(series_url):
    session = create_session_with_retries()
    response = fetch_url(series_url)
    
    if response is None:
        return []

    soup = BeautifulSoup(response.content, 'html.parser')
    episodes_area = soup.select_one('body > main > div.EpisodesArea')

    if not episodes_area:
        print("لم يتم العثور على منطقة الحلقات.")
        return []

    episodes = episodes_area.find_all('a')
    print(f"Found {len(episodes)} episodes.")
    episodes_info = []

    for episode in episodes:
        episode_link = episode['href']
        episode_order = episode.find('em').text.strip()
        episode_name = episode.get_text(strip=True).replace(f'الحلقة {episode_order}', '').strip()
        full_episode_url = get_full_episode_url(session, episode_link)
        
        if not full_episode_url:
            print(f"لم يتمكن من الحصول على رابط الحلقة الكامل لـ {episode_name}")
            continue
        
        watch_url = get_watch_url(session, full_episode_url)
        
        episodes_info.append({
            'episode_name': episode_name,
            'episode_order': episode_order,
            'episode_link': full_episode_url,
            'url': watch_url if watch_url else 'غير متوفر'
        })

    return episodes_info

# إنشاء تطبيق Flask
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/go', methods=['GET'])
def get_series_data():
    series_url = request.args.get('series_url')
    if not series_url:
        return jsonify({'error': 'مطلوب توفير رابط المسلسل'}), 400

    try:
        episodes_info = get_episodes_info(series_url)
        return jsonify(episodes_info)
    except requests.RequestException as e:
        return jsonify({'error': str(e)}), 500

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