from flask import Flask, request, jsonify
from bs4 import BeautifulSoup
import re
import time
import requests
import logging
from logging.handlers import RotatingFileHandler
import os
from urllib.parse import urljoin
import random

app = Flask(__name__)

# إعدادات متقدمة للتسجيل
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs')
os.makedirs(log_dir, exist_ok=True)

handler = RotatingFileHandler(os.path.join(log_dir, 'ahwak_scraper.log'), maxBytes=100000, backupCount=5)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[handler]
)
logger = logging.getLogger(__name__)

BASE_URL = "https://dal.ahwaktv.net"

class AdvancedBypasser:
    def __init__(self):
        self.session = requests.Session()
        self.update_headers()
        self.proxies = self.get_proxies()
        self.current_proxy = None
        
    def get_proxies(self):
        """قائمة بروكسيات احتياطية (يمكنك إضافة المزيد)"""
        return [
            None,  # بدون بروكسي أولاً
            # يمكنك إضافة بروكسيات أخرى هنا
        ]
    
    def update_headers(self):
        """تحديث الهيدرات بشكل عشوائي"""
        user_agents = [
            # قائمة كبيرة من User-Agents
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
        ]
        
        self.session.headers = {
            'User-Agent': random.choice(user_agents),
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'none',
            'Sec-Fetch-User': '?1',
            'Cache-Control': 'max-age=0',
            'TE': 'trailers',
        }
    
    def rotate_proxy(self):
        """تناوب البروكسي المستخدم"""
        self.current_proxy = random.choice(self.proxies)
        if self.current_proxy:
            self.session.proxies = {
                'http': self.current_proxy,
                'https': self.current_proxy
            }
        else:
            self.session.proxies = None
    
    def get_with_retry(self, url, max_retries=3):
        """إرسال طلب مع إعادة المحاولة"""
        for attempt in range(max_retries):
            try:
                self.update_headers()
                self.rotate_proxy()
                
                # تأخير عشوائي بين الطلبات
                time.sleep(random.uniform(1, 3))
                
                response = self.session.get(
                    url,
                    timeout=15,
                    allow_redirects=True
                )
                
                # إذا كان التحدي لا يزال موجوداً
                if response.status_code == 403 or "cloudflare" in response.text.lower():
                    logger.warning(f"Cloudflare challenge remains (Attempt {attempt + 1})")
                    continue
                
                return response
                
            except Exception as e:
                logger.error(f"Request failed (Attempt {attempt + 1}): {str(e)}")
                time.sleep(2 ** attempt)  # زيادة التأخير مع كل محاولة فاشلة
        
        return None

@app.route('/api/series', methods=['GET'])
def fetch_series_data():
    try:
        series_url = request.args.get('series_url')
        if not series_url:
            return jsonify({"success": False, "message": "يرجى تقديم رابط المسلسل"}), 400

        bypasser = AdvancedBypasser()
        response = bypasser.get_with_retry(series_url)
        
        if not response or response.status_code != 200:
            return jsonify({
                "success": False,
                "message": "فشل في جلب البيانات بعد عدة محاولات"
            }), 400

        soup = BeautifulSoup(response.text, 'html.parser')
        episodes_data = []

        episodes_list = soup.find('ul', class_='s')
        if not episodes_list:
            return jsonify({"success": False, "message": "لم يتم العثور على حلقات"}), 400

        for link in episodes_list.find_all('a'):
            try:
                episode_title = link.get('title', '')
                episode_url = urljoin(BASE_URL, link['href'])
                
                episode_number = re.search(r'الحلقة (\d+)', episode_title)
                if not episode_number:
                    continue
                    
                episode_number = int(episode_number.group(1))
                servers_url = episode_url.replace("watch.php", "see.php")
                
                # جلب بيانات السيرفرات
                time.sleep(random.uniform(0.5, 2.0))
                server_resp = bypasser.get_with_retry(servers_url)
                if not server_resp or server_resp.status_code != 200:
                    continue
                    
                server_soup = BeautifulSoup(server_resp.text, 'html.parser')
                server_div = server_soup.find('div', id='pm-servers')
                if not server_div:
                    continue
                
                # استخراج روابط التشغيل
                embed_url = None
                for server in server_div.find_all('li'):
                    url = server.get('data-embed-url', '')
                    if "hlswish.com" in url:
                        embed_url = url
                        break
                    elif "vidhideplus.com" in url:
                        embed_url = url
                
                if embed_url:
                    episodes_data.append({
                        "Episoade_Name": episode_title,
                        "episoade_order": episode_number,
                        "url": embed_url
                    })
                    
            except Exception as e:
                logger.error(f"Error processing episode: {str(e)}")
                continue

        return jsonify({"success": True, "episodes": episodes_data}), 200

    except Exception as e:
        logger.error(f"Unexpected error: {str(e)}")
        return jsonify({"success": False, "message": str(e)}), 500

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