import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
import re

class TopCinemaAPI:
    def __init__(self):
        self.base_url = "https://web6.topcinema.cam"
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': self.base_url
        }

    def get_movie_info(self, movie_url):
        """جلب معلومات الفيلم ورابط المشاهدة"""
        try:
            movie_url = self._clean_url(movie_url)
            response = requests.get(movie_url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'lxml')
            
            title = self._extract_title(soup)
            watch_url = self._get_watch_url(movie_url)
            play_url = self._get_final_play_url(watch_url) if watch_url else None
            
            return {
                "movie": {
                    "title": title,
                    "watch_url": watch_url,
                    "play_url": play_url
                },
                "success": True
            }
        except Exception as e:
            return {
                "error": str(e),
                "success": False
            }

    def get_series_info(self, series_url):
        """جلب معلومات المسلسل مع جميع المواسم والحلقات"""
        try:
            series_url = self._clean_url(series_url)
            response = requests.get(series_url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'lxml')
            
            title = self._extract_title(soup)
            seasons = self._extract_seasons(soup, series_url)
            
            if not seasons:
                episodes = self._extract_episodes_from_page(soup, series_url, "الموسم 1")
                if episodes:
                    seasons = [{
                        "season_name": "الموسم 1",
                        "episodes": episodes
                    }]
            
            return {
                "series": {
                    "title": title,
                    "seasons": seasons
                },
                "success": True
            }
        except Exception as e:
            return {
                "error": str(e),
                "success": False
            }

    def _extract_seasons(self, soup, base_url):
        """استخراج المواسم من صفحة المسلسل"""
        seasons = []
        season_elements = soup.select('div.Season--Item, div.season-item')
        
        for season in season_elements:
            season_link = season.find('a')
            if not season_link:
                continue
                
            season_url = urljoin(self.base_url, season_link['href'])
            season_title = self._extract_season_title(season)
            episodes = self._get_episodes_for_season(season_url, season_title)
            
            if episodes:
                seasons.append({
                    "season_name": season_title,
                    "season_url": season_url,
                    "episodes": episodes
                })
        
        return seasons

    def _get_episodes_for_season(self, season_url, season_title):
        """جلب الحلقات لموسم معين"""
        try:
            response = requests.get(season_url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'lxml')
            return self._extract_episodes_from_page(soup, season_url, season_title)
        except Exception as e:
            print(f"Error getting episodes: {e}")
            return []

    def _extract_episodes_from_page(self, soup, base_url, season_title):
        """استخراج الحلقات من صفحة الموسم"""
        episodes = []
        episode_elements = soup.select('div.Episode--Item, div.episode-item, div.Small--Box')
        
        for idx, episode in enumerate(episode_elements, start=1):
            episode_link = episode.find('a')
            if not episode_link:
                continue
                
            episode_url = urljoin(self.base_url, episode_link['href'])
            episode_title = self._extract_episode_title(episode, season_title)
            episode_number = self._extract_episode_number(episode_title) or idx
            
            watch_url = self._get_watch_url(episode_url)
            
            episodes.append({
                "episode_name": f"{episode_title}",
                "episode_number": episode_number,
                "watch_url": watch_url,
                "play_url": self._get_final_play_url(watch_url) if watch_url else None
            })
        
        episodes.sort(key=lambda x: x['episode_number'])
        return episodes

    def _get_watch_url(self, content_url):
        """بناء رابط المشاهدة"""
        try:
            # الطريقة 1: إضافة /watch مباشرة
            watch_url = f"{content_url.rstrip('/')}/watch"
            if self._check_url_exists(watch_url):
                return watch_url
            
            # الطريقة 2: بناء الرابط حسب الهيكل الجديد
            parsed = urlparse(content_url)
            path_parts = [p for p in parsed.path.split('/') if p]
            
            if 'مسلسل' in path_parts[0] or 'series' in path_parts[0].lower():
                new_path = f"/{path_parts[0]}-الحلقة-1-مترجمة/watch"
                watch_url = urljoin(self.base_url, new_path)
                if self._check_url_exists(watch_url):
                    return watch_url
                
            # الطريقة 3: البحث في الصفحة
            return self._find_watch_link_in_page(content_url)
        except Exception as e:
            print(f"Error building watch URL: {e}")
            return None

    def _get_final_play_url(self, watch_url):
        """جلب رابط التشغيل النهائي"""
        if not watch_url:
            return None
            
        try:
            response = requests.get(watch_url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'lxml')
            
            server_data = self._extract_server_data(soup)
            if not server_data:
                return None
                
            iframe_url = self._get_iframe_url(server_data['id'], server_data['server'])
            if not iframe_url:
                return None
                
            return self._process_special_hosts(iframe_url, server_data['host'])
        except Exception as e:
            print(f"Error getting final play URL: {e}")
            return None

    # باقي الدوال المساعدة...
    def _check_url_exists(self, url):
        try:
            response = requests.head(url, headers=self.headers, allow_redirects=True, timeout=5)
            return response.status_code == 200
        except:
            return False

    def _find_watch_link_in_page(self, content_url):
        try:
            response = requests.get(content_url, headers=self.headers)
            soup = BeautifulSoup(response.text, 'lxml')
            watch_btn = soup.find('a', {'href': re.compile(r'/watch')})
            if watch_btn:
                return urljoin(self.base_url, watch_btn['href'])
            iframe = soup.find('iframe')
            if iframe and iframe.get('src'):
                return iframe['src']
        except Exception as e:
            print(f"Error finding watch link: {e}")
        return None

    def _extract_server_data(self, soup):
        server_elements = soup.select('div.server-item')
        for server in server_elements:
            if 'active' in server.get('class', []):
                server_id = server.get('data-id')
                server_name = server.get('data-server')
                host_name = server.find('span', class_='server-name')
                if host_name:
                    host_name = host_name.get_text(strip=True)
                if server_id and server_name:
                    return {
                        'id': server_id,
                        'server': server_name,
                        'host': host_name
                    }
        return None

    def _get_iframe_url(self, server_id, server_name):
        api_url = f"{self.base_url}/wp-content/themes/movies2023/Ajaxat/Single/Server.php"
        payload = {
            'id': server_id,
            'i': server_name
        }
        try:
            response = requests.post(api_url, headers=self.headers, data=payload)
            iframe_pattern = re.compile(r'<iframe\s+src="([^"]+)"')
            match = iframe_pattern.search(response.text)
            if match:
                return match.group(1)
        except Exception as e:
            print(f"Error getting iframe URL: {e}")
        return None

    def _process_special_hosts(self, url, host):
        special_hosts = ['vidtube', 'vidhidepro', 'updown', 'ma2d', 'katomen', 'StreamWish']
        if any(h in (host or '') for h in special_hosts):
            return f"{url}|Referer={self.base_url}"
        return url

    def _clean_url(self, url):
        parsed = urlparse(url)
        return f"{parsed.scheme}://{parsed.netloc}{parsed.path}".rstrip('/')

    def _extract_title(self, soup):
        title_element = (soup.find('h1', class_='Title') or 
                        soup.find('h1', itemprop='name') or 
                        soup.find('div', class_='Title'))
        if title_element:
            title = title_element.get_text(strip=True)
            return re.sub(r'TopCinema|تــوب سينمـــا', '', title).strip()
        return "غير معروف"

    def _extract_season_title(self, element):
        title_element = (element.find('span', class_='Season--Number') or 
                        element.find('span', class_='season-number'))
        if title_element:
            return f"الموسم {title_element.get_text(strip=True)}"
        return "الموسم 1"

    def _extract_episode_title(self, element, season_title):
        title_element = (element.find('span', class_='Episode--Title') or 
                        element.find('div', class_='episode-title') or 
                        element.find('span', class_='epnum'))
        if title_element:
            return title_element.get_text(strip=True)
        return f"الحلقة"

    def _extract_episode_number(self, title):
        numbers = re.findall(r'\d+', title)
        return int(numbers[0]) if numbers else None