#!/usr/bin/env python3
"""
AK.SV BeautifulSoup Web Scraper - Improved Version
Comprehensive scraper with accurate detail extraction, proper download link following, and series episode support
"""

import requests
from bs4 import BeautifulSoup
import json
import time
import logging
import re
from typing import Dict, List, Optional
from urllib.parse import urljoin, urlparse, parse_qs
from cachetools import cached, TTLCache
import socket

# Force IPv4 to prevent "Network is unreachable" on systems without IPv6
old_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(*args, **kwargs):
    responses = old_getaddrinfo(*args, **kwargs)
    return [response for response in responses if response[0] == socket.AF_INET]
socket.getaddrinfo = new_getaddrinfo

from concurrent.futures import ThreadPoolExecutor, as_completed

# Configure logging
logging.basicConfig(
    level=logging.ERROR,  # Only show errors
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler()],  # Only stream to console
)
logger = logging.getLogger(__name__)

# Initialize cache: 1000 items, 1 hour TTL
scraper_cache = TTLCache(maxsize=1000, ttl=3600)


class AKSVBeautifulSoupScraper:
    """Comprehensive web scraper for ak.sv using BeautifulSoup4"""

    def __init__(self, delay: float = 1.0):
        """
        Initialize the scraper

        Args:
            delay: Delay between requests in seconds (rate limiting)
        """
        logger.info("Initializing AK.SV BeautifulSoup Scraper...")

        self.base_url = "https://akwam.com.co"
        self.delay = delay

        # Setup session with headers
        self.session = requests.Session()
        self.session.headers.update(
            {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
            }
        )

        logger.info("Scraper initialized successfully")

    def _get_page(self, url: str) -> Optional[BeautifulSoup]:
        """
        Fetch and parse a page

        Args:
            url: URL to fetch

        Returns:
            BeautifulSoup object or None if failed
        """
        try:
            logger.debug(f"Fetching: {url}")
            response = self.session.get(url, timeout=30)
            response.raise_for_status()

            # Add delay to avoid rate limiting
            time.sleep(self.delay)

            # Use lxml parser for better performance
            soup = BeautifulSoup(response.content, "lxml")

            return soup

        except Exception as e:
            logger.error(f"Failed to fetch {url}: {str(e)}")
            return None

    @cached(scraper_cache)
    def get_movies_list(self, page: int = 1) -> List[Dict]:
        """Get movies from a specific page"""
        try:
            url = (
                f"{self.base_url}/movies/page/{page}"
                if page > 1
                else f"{self.base_url}/movies"
            )
            logger.info(f"Fetching movies page {page}...")

            soup = self._get_page(url)
            if not soup:
                return []

            return self._extract_items_from_listing(soup, "movie")

        except Exception as e:
            logger.error(f"Failed to get movies list page {page}: {str(e)}")
            return []

    @cached(scraper_cache)
    def get_series_list(self, page: int = 1) -> List[Dict]:
        """Get series from a specific page"""
        try:
            url = (
                f"{self.base_url}/series/page/{page}"
                if page > 1
                else f"{self.base_url}/series"
            )
            logger.info(f"Fetching series page {page}...")

            soup = self._get_page(url)
            if not soup:
                return []

            return self._extract_items_from_listing(soup, "series")

        except Exception as e:
            logger.error(f"Failed to get series list page {page}: {str(e)}")
            return []

    @cached(scraper_cache)
    def search(
        self,
        query: str,
        section: str = "0",
        year: str = "0",
        rating: str = "0",
        formats: str = "0",
        quality: str = "0",
        page: int = 1,
    ) -> List[Dict]:
        """
        Search for movies and series with advanced filters

        Args:
            query: Search query
            section: Section filter (movie, series, etc.)
            year: Year filter
            rating: Rating filter
            formats: Format filter (BluRay, WEB-DL, etc.)
            quality: Quality filter (1080p, 720p, etc.)
            page: Page number

        Returns:
            List of dictionaries containing search results
        """
        try:
            # Construct URL with query parameters
            params = {
                "q": query,
                "section": section,
                "year": year,
                "rating": rating,
                "formats": formats,
                "quality": quality,
                "page": page,
            }
            # Remove default "0" values to keep URL clean (optional, but good practice if site supports it)
            # Based on debug html, site uses these params directly.

            # Use requests to build the query string correctly
            req = requests.Request("GET", f"{self.base_url}/search", params=params)
            prepped = req.prepare()
            url = prepped.url

            logger.info(f"Searching with URL: {url}")

            soup = self._get_page(url)
            if not soup:
                return []

            # Extract items using the entry-box container which holds all metadata
            items = []
            cards = soup.select("div.entry-box")

            for card in cards:
                try:
                    # Extract URL and Title
                    box_link = card.select_one("a.box")
                    if not box_link:
                        continue

                    url = box_link.get("href")
                    if not url:
                        continue

                    url = urljoin(self.base_url, url)

                    # Determine type
                    item_type = (
                        "movie"
                        if "/movie/" in url
                        else "series" if "/series/" in url else "unknown"
                    )
                    if item_type == "unknown":
                        continue

                    # Extract Title
                    title = ""
                    title_elem = card.select_one("h3.entry-title a")
                    if title_elem:
                        title = title_elem.get_text(strip=True)

                    # Extract Image
                    image = ""
                    img_elem = card.select_one("img")
                    if img_elem:
                        # Use data-src for lazy loaded images, fallback to src
                        image = img_elem.get("data-src") or img_elem.get("src")
                        if image:
                            image = urljoin(self.base_url, image)

                    # Extract Year
                    year = ""
                    year_elem = card.select_one(".badge-secondary")  # usually year
                    if year_elem:
                        year = year_elem.get_text(strip=True)

                    # Extract Rating
                    rating = ""
                    rating_elem = card.select_one(".label.rating")
                    if rating_elem:
                        rating = rating_elem.get_text(strip=True)

                    # Extract Quality
                    quality = ""
                    quality_elem = card.select_one(".label.quality")
                    if quality_elem:
                        quality = quality_elem.get_text(strip=True)

                    # Extract Genres
                    genres = []
                    genre_elems = card.select(".badge-light")
                    for g in genre_elems:
                        genres.append(g.get_text(strip=True))

                    items.append(
                        {
                            "title": title,
                            "url": url,
                            "image": image,
                            "year": year,
                            "rating": rating,
                            "quality": quality,
                            "genres": genres,
                            "type": item_type,
                        }
                    )

                except Exception as e:
                    logger.debug(f"Error extracting search item: {str(e)}")
                    continue

            logger.info(f"Found {len(items)} results for '{query}'")
            return items

        except Exception as e:
            logger.error(f"Search failed: {str(e)}")
            return []

    def _extract_items_from_listing(
        self, soup: BeautifulSoup, item_type: str
    ) -> List[Dict]:
        """Extract items from a listing page"""
        items = []

        # Find all movie/series cards using ak.sv specific selector
        cards = soup.select("a.box")

        logger.info(f"Found {len(cards)} {item_type} cards")

        seen_urls = set()

        for card in cards:
            try:
                # Extract URL from the card link
                url = card.get("href")
                if not url:
                    continue

                # Make absolute URL
                url = urljoin(self.base_url, url)

                # Filter by item type
                if f"/{item_type}/" not in url:
                    continue

                # Skip duplicates
                if url in seen_urls:
                    continue
                seen_urls.add(url)

                # Extract title from h3 inside the card
                title = ""
                title_elem = card.select_one("h3")
                if title_elem:
                    title = title_elem.get_text(strip=True)
                else:
                    # Fallback: extract from URL slug
                    url_parts = url.rstrip("/").split("/")
                    if len(url_parts) > 0:
                        title = url_parts[-1].replace("-", " ").title()

                # Extract image
                image = ""
                img_elem = card.select_one("img")
                if img_elem:
                    image = img_elem.get("src") or img_elem.get("data-src", "")
                    if image:
                        image = urljoin(self.base_url, image)

                # Extract year from badge if visible
                year = ""
                year_elem = card.select_one(".badge, .year")
                if year_elem:
                    year_text = year_elem.get_text(strip=True)
                    year_match = re.search(r"\\d{4}", year_text)
                    if year_match:
                        year = year_match.group(0)

                items.append(
                    {
                        "title": title,
                        "url": url,
                        "image": image,
                        "year": year,
                        "type": item_type,
                    }
                )

            except Exception as e:
                logger.debug(f"Error extracting item: {str(e)}")
                continue

        logger.info(f"Extracted {len(items)} {item_type}s from page")
        return items

    def get_all_movies(self, max_pages: int = 5) -> List[Dict]:
        """Get all movies with pagination"""
        all_movies = []

        for page in range(1, max_pages + 1):
            movies = self.get_movies_list(page)
            if not movies:
                logger.info(f"No more movies found at page {page}, stopping")
                break

            all_movies.extend(movies)
            logger.info(f"Total movies collected: {len(all_movies)}")

        return all_movies

    def get_all_series(self, max_pages: int = 5) -> List[Dict]:
        """Get all series with pagination"""
        all_series = []

        for page in range(1, max_pages + 1):
            series = self.get_series_list(page)
            if not series:
                logger.info(f"No more series found at page {page}, stopping")
                break

            all_series.extend(series)
            logger.info(f"Total series collected: {len(all_series)}")

        return all_series

    @cached(scraper_cache)
    def get_movie_details(self, url: str) -> Dict:
        """Extract complete details from a movie page"""
        try:
            logger.info(f"Extracting movie details from: {url}")

            soup = self._get_page(url)
            if not soup:
                return {}

            details = {
                "url": url,
                "title": "",
                "rating": "",
                "year": "",
                "duration": "",
                "language": "",
                "quality": "",
                "genres": [],
                "synopsis": "",
                "cast": [],
                "imdb_link": "",
                "trailer_link": "",
                "poster": "",
                "gallery_images": [],
                "download_links": [],
                "type": "movie",
            }

            # Extract title
            title_elem = soup.select_one("h1")
            if title_elem:
                details["title"] = title_elem.get_text(strip=True)

            # Extract metadata - comprehensive approach
            # Get all page text for parsing
            page_text = soup.get_text()

            # Try to extract from JSON-LD first (most reliable)
            json_ld_data = {}
            try:
                json_ld_script = soup.select_one('script[type="application/ld+json"]')
                if json_ld_script:
                    data = json.loads(json_ld_script.string)
                    if isinstance(data, list):
                        for item in data:
                            if (
                                item.get("@type") == "Movie"
                                or item.get("@type") == "TVSeries"
                            ):
                                json_ld_data = item
                                break
                    elif isinstance(data, dict):
                        if (
                            data.get("@type") == "Movie"
                            or data.get("@type") == "TVSeries"
                        ):
                            json_ld_data = data
            except Exception as e:
                logger.debug(f"Error parsing JSON-LD: {str(e)}")

            # Use JSON-LD data if available
            if json_ld_data:
                if not details["title"] and json_ld_data.get("name"):
                    details["title"] = json_ld_data["name"]

                if json_ld_data.get("image"):
                    if isinstance(json_ld_data["image"], list):
                        details["poster"] = json_ld_data["image"][0]
                    elif isinstance(json_ld_data["image"], str):
                        details["poster"] = json_ld_data["image"]

                if json_ld_data.get("AggregateRating") and isinstance(
                    json_ld_data["AggregateRating"], dict
                ):
                    details["rating"] = json_ld_data["AggregateRating"].get(
                        "ratingValue", ""
                    )

                if json_ld_data.get("datePublished"):
                    year_match = re.search(r"(\d{4})", json_ld_data["datePublished"])
                    if year_match:
                        details["year"] = year_match.group(1)

                if json_ld_data.get("description"):
                    details["synopsis"] = json_ld_data["description"]

            # Fallback/Additional extraction

            # Extract year - look for Arabic pattern "السنة : YYYY" or just 4-digit year
            if not details["year"]:
                # Try Arabic pattern first
                year_match = re.search(r"السنة\s*:\s*(\d{4})", page_text)
                if year_match:
                    details["year"] = year_match.group(1)
                else:
                    # Try finding any 4-digit year
                    year_match = re.search(r"\b(19|20)\d{2}\b", page_text)
                    if year_match:
                        details["year"] = year_match.group(0)

            # Extract duration - look for Arabic pattern "مدة الفيلم : XXX دقيقة"
            if not details["duration"]:
                duration_match = re.search(
                    r"مدة\s+الفيلم\s*:\s*(\d+)\s*دقيقة", page_text
                )
                if duration_match:
                    details["duration"] = duration_match.group(1) + " دقيقة"
                else:
                    # Try English pattern
                    duration_match = re.search(
                        r"(\d+)\s*(?:min|minutes)", page_text, re.IGNORECASE
                    )
                    if duration_match:
                        details["duration"] = duration_match.group(0)

            # Extract language
            if "إنجليزي" in page_text or "English" in page_text:
                details["language"] = "English"
            elif "عربي" in page_text or "Arabic" in page_text:
                details["language"] = "Arabic"

            # Extract quality from filename or text
            quality_match = re.search(
                r"(BluRay|WEB-DL|HDRip|DVDRip|CAM|HD|1080p|720p|480p)",
                page_text,
                re.IGNORECASE,
            )
            if quality_match:
                details["quality"] = quality_match.group(0)

            # Extract genres - look for badges in the header section
            # They are usually in a div with class "font-size-16 d-flex align-items-center mt-3"
            # Or just look for the specific badge class structure globally but exclude "Watch More" section

            # First try to find the main header container
            header_container = soup.select_one(".col-lg-7") or soup
            genre_badges = header_container.select(
                'a.badge.badge-pill.badge-light.ml-2[href*="/movies?category="], a.badge.badge-pill.badge-light.ml-2[href*="/series?category="]'
            )

            if genre_badges:
                details["genres"] = [
                    g.get_text(strip=True)
                    for g in genre_badges
                    if g.get_text(strip=True) and len(g.get_text(strip=True)) > 2
                ]
            else:
                # Fallback
                genre_links = soup.select('a[href*="/genre/"]')
                if genre_links:
                    details["genres"] = [
                        g.get_text(strip=True)
                        for g in genre_links[:5]
                        if g.get_text(strip=True)
                    ]

            # Extract synopsis if not found in JSON-LD
            if not details["synopsis"]:
                story_paragraphs = soup.select(".widget-body p")
                for p in story_paragraphs:
                    text = p.get_text(strip=True)
                    if len(text) > 100 and (
                        "حيث يدور" in text or "مشاهدة و تحميل" in text
                    ):
                        # Clean up the synopsis
                        synopsis = (
                            text.replace("مشاهدة و تحميل فيلم", "")
                            .replace("حيث يدور العمل حول", "")
                            .strip()
                        )
                        if synopsis:
                            details["synopsis"] = synopsis
                        break

            # Extract cast
            cast_links = soup.select('a[href*="/person/"]')
            details["cast"] = [
                c.get_text(strip=True) for c in cast_links if c.get_text(strip=True)
            ]

            # Extract IMDB link
            imdb_link = soup.select_one('a[href*="imdb.com"]')
            if imdb_link:
                details["imdb_link"] = imdb_link.get("href", "")

            # Extract trailer link
            trailer_link = soup.select_one(
                'a[href*="youtube.com"], a[href*="youtu.be"]'
            )
            if trailer_link:
                details["trailer_link"] = trailer_link.get("href", "")

            # Extract poster if not found in JSON-LD
            if not details["poster"]:
                # Try OG Image
                og_image = soup.select_one('meta[property="og:image"]')
                if og_image:
                    details["poster"] = og_image.get("content", "")

                if not details["poster"]:
                    poster_elem = soup.select_one('.poster img, img[itemprop="image"]')
                    if poster_elem:
                        poster_url = poster_elem.get("src") or poster_elem.get(
                            "data-src", ""
                        )
                        if poster_url:
                            details["poster"] = urljoin(self.base_url, poster_url)

            # Extract gallery images
            details["gallery_images"] = self.get_gallery_images(soup)

            # Extract download links
            details["download_links"] = self.get_download_links(soup)

            logger.info(f"Successfully extracted details for: {details['title']}")
            return details

        except Exception as e:
            logger.error(f"Failed to extract movie details: {str(e)}")
            return {}

    @cached(scraper_cache)
    def get_series_details(self, url: str) -> Dict:
        """Extract complete details from a series page including episodes"""
        try:
            logger.info(f"Extracting series details from: {url}")

            soup = self._get_page(url)
            if not soup:
                return {}

            details = {
                "url": url,
                "title": "",
                "rating": "",
                "year": "",
                "genres": [],
                "synopsis": "",
                "cast": [],
                "imdb_link": "",
                "trailer_link": "",
                "poster": "",
                "gallery_images": [],
                "episodes": [],
                "type": "series",
            }

            # Extract title
            title_elem = soup.select_one("h1")
            if title_elem:
                details["title"] = title_elem.get_text(strip=True)

            # Extract metadata
            widget_body = soup.select_one(".widget-body")
            # Extract metadata - comprehensive approach
            page_text = soup.get_text()

            # Try to extract from JSON-LD first (most reliable)
            json_ld_data = {}
            try:
                json_ld_script = soup.select_one('script[type="application/ld+json"]')
                if json_ld_script:
                    data = json.loads(json_ld_script.string)
                    if isinstance(data, list):
                        for item in data:
                            if (
                                item.get("@type") == "TVSeries"
                                or item.get("@type") == "Movie"
                            ):
                                json_ld_data = item
                                break
                    elif isinstance(data, dict):
                        if (
                            data.get("@type") == "TVSeries"
                            or data.get("@type") == "Movie"
                        ):
                            json_ld_data = data
            except Exception as e:
                logger.debug(f"Error parsing JSON-LD: {str(e)}")

            # Use JSON-LD data if available
            if json_ld_data:
                if not details["title"] and json_ld_data.get("name"):
                    details["title"] = json_ld_data["name"]

                if json_ld_data.get("image"):
                    if isinstance(json_ld_data["image"], list):
                        details["poster"] = json_ld_data["image"][0]
                    elif isinstance(json_ld_data["image"], str):
                        details["poster"] = json_ld_data["image"]

                if json_ld_data.get("AggregateRating") and isinstance(
                    json_ld_data["AggregateRating"], dict
                ):
                    details["rating"] = json_ld_data["AggregateRating"].get(
                        "ratingValue", ""
                    )

                if json_ld_data.get("datePublished") or json_ld_data.get("startDate"):
                    date_str = json_ld_data.get("datePublished") or json_ld_data.get(
                        "startDate"
                    )
                    year_match = re.search(r"(\d{4})", date_str)
                    if year_match:
                        details["year"] = year_match.group(1)

                if json_ld_data.get("description"):
                    details["synopsis"] = json_ld_data["description"]

            # Fallback/Additional extraction

            # Extract year
            if not details["year"]:
                widget_body = soup.select_one(".widget-body")
                if widget_body:
                    text_content = widget_body.get_text()
                    year_match = re.search(r"\b(19|20)\d{2}\b", text_content)
                    if year_match:
                        details["year"] = year_match.group(0)

            # Extract genres - look for badges in the header section
            # First try to find the main header container
            header_container = soup.select_one(".col-lg-7") or soup
            genre_badges = header_container.select(
                'a.badge.badge-pill.badge-light.ml-2[href*="/series?category="], a.badge.badge-pill.badge-light.ml-2[href*="/movies?category="]'
            )

            if genre_badges:
                details["genres"] = [
                    g.get_text(strip=True)
                    for g in genre_badges
                    if g.get_text(strip=True) and len(g.get_text(strip=True)) > 2
                ]
            else:
                # Fallback
                genre_links = soup.select('a[href*="/genre/"]')
                if genre_links:
                    details["genres"] = [
                        g.get_text(strip=True)
                        for g in genre_links[:5]
                        if g.get_text(strip=True)
                    ]

            # Extract synopsis if not found in JSON-LD
            if not details["synopsis"]:
                story_paragraphs = soup.select(".widget-body p")
                for p in story_paragraphs:
                    text = p.get_text(strip=True)
                    if len(text) > 100 and (
                        "حيث يدور" in text or "مشاهدة و تحميل" in text
                    ):
                        synopsis = (
                            text.replace("مشاهدة و تحميل  مسلسل", "")
                            .replace("مسلسل", "")
                            .replace("حيث يدور العمل حول", "")
                            .strip()
                        )
                        if synopsis:
                            details["synopsis"] = synopsis
                        break

            # Extract cast
            cast_links = soup.select('a[href*="/person/"]')
            details["cast"] = [
                c.get_text(strip=True) for c in cast_links if c.get_text(strip=True)
            ]

            # Extract IMDB link
            imdb_link = soup.select_one('a[href*="imdb.com"]')
            if imdb_link:
                details["imdb_link"] = imdb_link.get("href", "")

            # Extract trailer link
            trailer_link = soup.select_one(
                'a[href*="youtube.com"], a[href*="youtu.be"]'
            )
            if trailer_link:
                details["trailer_link"] = trailer_link.get("href", "")

            # Extract poster if not found in JSON-LD
            if not details["poster"]:
                # Try OG Image
                og_image = soup.select_one('meta[property="og:image"]')
                if og_image:
                    details["poster"] = og_image.get("content", "")

                if not details["poster"]:
                    poster_elem = soup.select_one('.poster img, img[itemprop="image"]')
                    if poster_elem:
                        poster_url = poster_elem.get("src") or poster_elem.get(
                            "data-src", ""
                        )
                        if poster_url:
                            details["poster"] = urljoin(self.base_url, poster_url)

            # Extract gallery images
            details["gallery_images"] = self.get_gallery_images(soup)

            # Extract episodes
            details["episodes"] = self.get_episodes(soup)

            logger.info(
                f"Successfully extracted details for series: {details['title']} ({len(details['episodes'])} episodes)"
            )
            return details

        except Exception as e:
            logger.error(f"Failed to extract series details: {str(e)}")
            return {}

    def get_episodes(self, soup: BeautifulSoup) -> List[Dict]:
        """Extract episode list from series page"""
        try:
            logger.info("Extracting episodes...")

            episodes = []

            # Find all episode links
            episode_links = soup.select('a[href*="/episode/"]')

            logger.info(f"Found {len(episode_links)} episode links")

            seen_urls = set()

            for link in episode_links:
                try:
                    url = link.get("href")
                    if not url or url in seen_urls:
                        continue

                    seen_urls.add(url)
                    url = urljoin(self.base_url, url)

                    # Extract episode title/number
                    title = link.get_text(strip=True)

                    # Try to extract episode number
                    episode_num = ""
                    num_match = re.search(r"(\d+)", title)
                    if num_match:
                        episode_num = num_match.group(1)

                    episodes.append(
                        {"title": title, "episode_number": episode_num, "url": url}
                    )

                except Exception as e:
                    logger.debug(f"Error extracting episode: {str(e)}")
                    continue

            # Sort episodes by number if available
            episodes.sort(
                key=lambda x: (
                    int(x["episode_number"]) if x["episode_number"].isdigit() else 0
                )
            )

            logger.info(f"Extracted {len(episodes)} episodes")
            return episodes

        except Exception as e:
            logger.error(f"Failed to extract episodes: {str(e)}")
            return []

    @cached(scraper_cache)
    def get_episode_details(self, url: str) -> Dict:
        """Extract details from an episode page"""
        try:
            logger.info(f"Extracting episode details from: {url}")

            soup = self._get_page(url)
            if not soup:
                return {}

            details = {
                "url": url,
                "title": "",
                "episode_number": "",
                "season_number": "",
                "release_date": "",
                "synopsis": "",
                "download_links": [],
                "type": "episode",
            }

            # Extract title
            title_elem = soup.select_one("h1")
            if title_elem:
                details["title"] = title_elem.get_text(strip=True)

                # Try to extract episode/season numbers from title
                ep_match = re.search(
                    r"(?:حلقة|episode|ep)\s*(\d+)", details["title"], re.IGNORECASE
                )
                if ep_match:
                    details["episode_number"] = ep_match.group(1)

                season_match = re.search(
                    r"(?:موسم|season|s)\s*(\d+)", details["title"], re.IGNORECASE
                )
                if season_match:
                    details["season_number"] = season_match.group(1)

            # Extract metadata from page text
            page_text = soup.get_text()

            # Extract release date
            date_match = re.search(r"تـ الإضافة\s*:\s*([^\n]+)", page_text)
            if date_match:
                details["release_date"] = date_match.group(1).strip()

            # Extract synopsis
            story_paragraphs = soup.select(".widget-body p")
            for p in story_paragraphs:
                text = p.get_text(strip=True)
                if len(text) > 50 and "مشاهدة" not in text[:20]:
                    details["synopsis"] = text
                    break

            # Extract download links
            details["download_links"] = self.get_download_links(soup)

            logger.info(f"Successfully extracted episode details: {details['title']}")
            return details

        except Exception as e:
            logger.error(f"Failed to extract episode details: {str(e)}")
            return {}

    def get_gallery_images(self, soup: BeautifulSoup) -> List[str]:
        """Extract full-size gallery images from anchor hrefs (not thumbnails)"""
        images = []

        # Find all anchor tags with image hrefs in the story/gallery section
        # These contain full-size image URLs
        story_section = soup.select_one(".widget-body") or soup

        # Look for anchor tags with href containing /uploads/
        image_links = story_section.select('a[href*="/uploads/"]')

        for link in image_links:
            href = link.get("href", "")
            if href and "/uploads/" in href:
                # Check if this is an image file (not a video or other file)
                if any(
                    ext in href.lower()
                    for ext in [".jpg", ".jpeg", ".png", ".webp", ".gif"]
                ):
                    full_url = urljoin(self.base_url, href)
                    # Exclude logos, icons, and small images
                    if not any(
                        x in href.lower()
                        for x in [
                            "logo",
                            "icon",
                            "tmdb",
                            "imdb",
                            "placeholder",
                            "54x54",
                            "32x32",
                        ]
                    ):
                        if full_url not in images:
                            images.append(full_url)
                # If no extension, assume it's an image if the link contains an img tag
                elif link.select_one("img"):
                    full_url = urljoin(self.base_url, href)
                    if not any(
                        x in href.lower()
                        for x in [
                            "logo",
                            "icon",
                            "tmdb",
                            "imdb",
                            "placeholder",
                            "54x54",
                            "32x32",
                        ]
                    ):
                        if full_url not in images:
                            images.append(full_url)

        logger.info(f"Found {len(images)} full-size gallery images")
        return images

    def get_download_links(self, soup: BeautifulSoup) -> List[Dict]:
        """Extract download links for all quality options"""
        try:
            logger.info("Extracting download links...")

            download_data = []

            # Find quality tabs
            quality_tabs = soup.select('a[href^="#tab-"]')

            if not quality_tabs:
                logger.warning("No quality tabs found")
                return []

            logger.info(f"Found {len(quality_tabs)} quality tabs")

            # For each quality tab, find the corresponding content
            for tab in quality_tabs:
                try:
                    quality = tab.get_text(strip=True)
                    tab_id = tab.get("href", "").replace("#", "")

                    if not tab_id:
                        continue

                    # Find the tab content
                    tab_content = soup.select_one(f"#{tab_id}")

                    if not tab_content:
                        # Try to find download links near the tab
                        parent = tab.find_parent()
                        if parent:
                            # Look for download links in the next siblings
                            next_sibling = parent.find_next_sibling()
                            if next_sibling:
                                tab_content = next_sibling

                    if not tab_content:
                        # Fallback: find all download links and match by position
                        all_download_links = soup.select(
                            'a[href*="/link/"], a.link-download'
                        )
                        if all_download_links:
                            tab_index = quality_tabs.index(tab)
                            if tab_index < len(all_download_links):
                                # Create a temporary container
                                tab_content = all_download_links[tab_index].parent

                    if not tab_content:
                        logger.debug(f"Could not find content for {quality}")
                        continue

                    # Extract watch link (just store it, don't follow redirects)
                    watch_link = ""
                    watch_elem = tab_content.select_one('a[href*="/watch/"]')
                    if watch_elem:
                        watch_link = watch_elem.get("href", "")
                        if watch_link:
                            watch_link = urljoin(self.base_url, watch_link)

                    # Extract download link
                    download_link = ""
                    size = ""
                    download_elem = tab_content.select_one('a[href*="/link/"]')
                    if download_elem:
                        download_link = download_elem.get("href", "")
                        if download_link:
                            download_link = urljoin(self.base_url, download_link)

                        # Extract size from download button text
                        button_text = download_elem.get_text(strip=True)
                        button_text = button_text.replace("تحميل", " ")
                        size_match = re.search(
                            r"([\d.]+\s*[GMK]B)", button_text, re.IGNORECASE
                        )
                        if size_match:
                            size = size_match.group(1).strip()

                    if download_link:
                        download_data.append(
                            {
                                "quality": quality,
                                "watch_link": watch_link,
                                "download_link": download_link,
                                "size": size,
                            }
                        )
                        logger.info(f"Extracted {quality}: {size}")

                except Exception as e:
                    logger.debug(f"Error extracting quality tab: {str(e)}")
                    continue

            logger.info(
                f"Collected {len(download_data)} download links, resolving final URLs in parallel..."
            )

            # Resolve final URLs in parallel using ThreadPoolExecutor
            if download_data:

                def resolve_url(item):
                    """Resolve final download URL for a single item"""
                    try:
                        final_url = self.get_final_download_url(item["download_link"])
                        return {
                            **item,
                            "final_download_url": final_url,
                            "final_watch_url": final_url,
                        }
                    except Exception as e:
                        logger.error(f"Error resolving URL: {e}")
                        return {
                            **item,
                            "final_download_url": item["download_link"],
                            "final_watch_url": item["download_link"],
                        }

                # Use ThreadPoolExecutor for parallel resolution
                with ThreadPoolExecutor(max_workers=4) as executor:
                    download_data = list(executor.map(resolve_url, download_data))

            logger.info(f"Resolved {len(download_data)} download links")
            return download_data

        except Exception as e:
            logger.error(f"Failed to extract download links: {str(e)}")
            return []

    def get_final_download_url(self, redirect_url: str) -> str:
        """
        Follow redirect chain to get direct file download URL

        The redirect chain is:
        1. http://go.ak.sv/link/XXXXX -> https://go.ak.sv/link/XXXXX
        2. https://go.ak.sv/link/XXXXX -> https://ak.sv/download/XXXXX/...
        3. https://ak.sv/download/XXXXX/... -> https://sXXX.downet.net/download/.../file.mp4
        """
        try:
            logger.debug(f"Following redirect: {redirect_url}")

            # Step 1: Follow redirects to get to go.ak.sv page
            response = self.session.get(redirect_url, allow_redirects=True, timeout=15)
            soup = BeautifulSoup(response.content, "lxml")

            # Step 2: Find ak.sv/download link
            download_page_link = soup.select_one('a[href*="/download/"]')
            if download_page_link:
                download_page_url = download_page_link.get("href", "")
                if download_page_url:
                    download_page_url = urljoin(response.url, download_page_url)
                    logger.debug(f"Found download page: {download_page_url}")

                    # Step 3: Get the download page and find direct file link
                    time.sleep(0.5)  # Small delay
                    download_response = self.session.get(
                        download_page_url, allow_redirects=True, timeout=15
                    )
                    download_soup = BeautifulSoup(download_response.content, "lxml")

                    # Look for direct download link (downet.net or similar CDN)
                    # Pattern: https://sXXX.downet.net/download/.../file.mp4
                    direct_links = download_soup.select(
                        'a[href*="downet.net"], a[href*=".mp4"], a[href*=".mkv"]'
                    )
                    for link in direct_links:
                        href = link.get("href", "")
                        if href and (
                            "/download/" in href
                            or href.endswith((".mp4", ".mkv", ".avi"))
                        ):
                            direct_url = urljoin(download_response.url, href)
                            logger.info(f"Found direct file URL: {direct_url}")
                            return direct_url

                    # If no direct link found, return download page URL
                    logger.info(
                        f"No direct file link found, returning download page: {download_page_url}"
                    )
                    return download_page_url

            # Fallback: return what we have
            logger.warning(f"Could not find download link, returning: {response.url}")
            return response.url

        except Exception as e:
            logger.error(f"Failed to get final download URL: {str(e)}")
            return redirect_url

    def export_to_json(self, data: Dict, filename: str = "ak_sv_bs4_data.json"):
        """Export scraped data to JSON file - DISABLED"""
        pass


def main():
    """Demo/test function"""
    try:
        # Initialize scraper
        scraper = AKSVBeautifulSoupScraper(delay=1.0)

        logger.info("=== Starting demo scrape ===")

        result = {
            "movies": [],
            "series": [],
            "movie_details": [],
            "series_details": [],
            "episode_details": [],
        }

        # Get movies from first page
        logger.info("\\n--- Fetching Movies ---")
        movies = scraper.get_movies_list(1)
        result["movies"] = movies
        logger.info(f"Total movies fetched: {len(movies)}")

        # Get series from first page
        logger.info("\\n--- Fetching Series ---")
        series = scraper.get_series_list(1)
        result["series"] = series
        logger.info(f"Total series fetched: {len(series)}")

        # Get details for first 2 movies
        logger.info("\\n--- Fetching Movie Details ---")
        for i, movie in enumerate(movies[:2]):
            logger.info(f"Processing movie {i+1}/2: {movie['title']}")
            details = scraper.get_movie_details(movie["url"])
            if details:
                result["movie_details"].append(details)

        # Get details for first 2 series (with episodes)
        logger.info("\\n--- Fetching Series Details ---")
        for i, show in enumerate(series[:2]):
            logger.info(f"Processing series {i+1}/2: {show['title']}")
            details = scraper.get_series_details(show["url"])
            if details:
                result["series_details"].append(details)

                # Get details for first episode of first series
                if i == 0 and details.get("episodes"):
                    first_episode = details["episodes"][0]
                    logger.info(f"Fetching episode details: {first_episode['title']}")
                    episode_details = scraper.get_episode_details(first_episode["url"])
                    if episode_details:
                        result["episode_details"].append(episode_details)

        # Export results
        # scraper.export_to_json(result)

        # Print summary
        # print("\\n" + "=" * 60)
        # print("SCRAPING SUMMARY")
        # print("=" * 60)
        # print(f"Movies Listed: {len(result['movies'])}")
        # print(f"Series Listed: {len(result['series'])}")
        # print(f"Movie Details Extracted: {len(result['movie_details'])}")
        # print(f"Series Details Extracted: {len(result['series_details'])}")
        # print(f"Episode Details Extracted: {len(result['episode_details'])}")

        # print("\\n--- Movie Details ---")
        # for i, movie in enumerate(result["movie_details"], 1):
        #     print(f"\\n{i}. {movie.get('title', 'Unknown')}")
        #     print(f"   Year: {movie.get('year', 'N/A')}")
        #     print(f"   Duration: {movie.get('duration', 'N/A')}")
        #     print(f"   Genres: {', '.join(movie.get('genres', []))}")
        #     print(f"   Cast: {len(movie.get('cast', []))} members")
        #     print(f"   Gallery: {len(movie.get('gallery_images', []))} images")
        #     print(f"   Downloads: {len(movie.get('download_links', []))} options")

        #     for dl in movie.get("download_links", []):
        #         print(
        #             f"      - {dl.get('quality', 'Unknown')}: {dl.get('size', 'N/A')}"
        #         )
        #         print(f"        Final URL: {dl.get('final_download_url', 'N/A')}")

        # print("\\n--- Series Details ---")
        # for i, show in enumerate(result["series_details"], 1):
        #     print(f"\\n{i}. {show.get('title', 'Unknown')}")
        #     print(f"   Year: {show.get('year', 'N/A')}")
        #     print(f"   Genres: {', '.join(show.get('genres', []))}")
        #     print(f"   Cast: {len(show.get('cast', []))} members")
        #     print(f"   Episodes: {len(show.get('episodes', []))}")

        #     # Show first 3 episodes
        #     for ep in show.get("episodes", [])[:3]:
        #         print(f"      - {ep.get('title', 'Unknown')}")

        # print("\\n--- Episode Details ---")
        # for i, episode in enumerate(result["episode_details"], 1):
        #     print(f"\\n{i}. {episode.get('title', 'Unknown')}")
        #     print(f"   Downloads: {len(episode.get('download_links', []))} options")
        #     for dl in episode.get("download_links", []):
        #         print(
        #             f"      - {dl.get('quality', 'Unknown')}: {dl.get('size', 'N/A')}"
        #         )

        # print("\\n" + "=" * 60)
        # print(f"Full data saved to: ak_sv_bs4_data.json")
        # print("=" * 60)

    except KeyboardInterrupt:
        logger.info("Scraping interrupted by user")
    except Exception as e:
        logger.error(f"Error in main: {str(e)}")


if __name__ == "__main__":
    main()
