"""IMDb site preset."""
import re
import json


class IMDb:
    def __init__(self, client):
        self.client = client

    def extract(self, url):
        try:
            headers = {
                "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/avif,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.9",
                "Accept-Encoding": "gzip, deflate, br",
                "Sec-Ch-Ua": '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
                "Sec-Ch-Ua-Mobile": "?0",
                "Sec-Ch-Ua-Platform": '"Windows"',
                "Sec-Fetch-Dest": "document",
                "Sec-Fetch-Mode": "navigate",
                "Sec-Fetch-Site": "none",
                "Sec-Fetch-User": "?1",
                "Upgrade-Insecure-Requests": "1",
            }
            # Try via proxy (IMDb blocks most direct requests)
            try:
                resp = self.client.fetch(url, country="US", headers=headers, timeout=15)
                html = resp.text
            except Exception:
                resp = self.client.fetch(url, headers=headers, timeout=15)
                html = resp.text

            data = {}
            # Try JSON-LD
            ld_match = re.search(r'<script type="application/ld\+json">(.*?)</script>', html, re.DOTALL)
            if ld_match:
                ld = json.loads(ld_match.group(1))
                data["title"] = ld.get("name")
                data["rating"] = (ld.get("aggregateRating") or {}).get("ratingValue")
                data["year"] = (ld.get("datePublished") or "")[:4] or None
                genre = ld.get("genre")
                data["genre"] = genre if isinstance(genre, list) else [genre] if genre else []
                data["description"] = ld.get("description")
            else:
                t = re.search(r'<title>(.*?)</title>', html)
                if t:
                    data["title"] = t.group(1)

            # If still empty, try OMDB with IMDb ID
            if not data.get("title"):
                imdb_id_match = re.search(r'(tt\d+)', url)
                if imdb_id_match:
                    imdb_id = imdb_id_match.group(1)
                    data["imdb_id"] = imdb_id
                    data["title"] = f"IMDb: {imdb_id} (proxy needed for full data)"

            return {"success": bool(data.get("title")), "data": data, "source": "imdb-http", "error": None}
        except Exception as e:
            return {"success": False, "data": {}, "source": "imdb-http", "error": str(e)}
