"""CNN site preset."""
import re


class CNN:
    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"}
            resp = self.client.fetch(url, headers=headers, timeout=20)
            if resp.status_code != 200:
                return {"success": False, "data": {}, "source": "cnn-http", "error": f"HTTP {resp.status_code}"}

            html = resp.text
            data = {}

            t = re.search(r'<title>([^<]*)</title>', html)
            if t:
                data["title"] = t.group(1).strip()

            desc = re.search(r'<meta name="description" content="([^"]*)"', html)
            if desc:
                data["description"] = desc.group(1)[:300]

            # Author from JSON-LD
            author = re.search(r'"author"\s*:\s*\[\s*\{[^}]*"name"\s*:\s*"([^"]*)"', html)
            if not author:
                author = re.search(r'"author"\s*:\s*\{[^}]*"name"\s*:\s*"([^"]*)"', html)
            if author:
                data["author"] = author.group(1)

            # Published date
            pub = re.search(r'"datePublished"\s*:\s*"([^"]*)"', html)
            if pub:
                data["published_date"] = pub.group(1)

            # If homepage, extract article links
            if url.rstrip("/").endswith("cnn.com") or "/index.html" in url:
                articles = []
                for m in re.finditer(r'<a[^>]*href="(https://www\.cnn\.com/\d{4}/\d{2}/\d{2}/[^"]+)"[^>]*>([^<]*)<', html):
                    title_text = m.group(2).strip()
                    if title_text and len(title_text) > 10:
                        articles.append({"url": m.group(1), "title": title_text})
                if not articles:
                    for m in re.finditer(r'<a[^>]*href="(/\d{4}/\d{2}/\d{2}/[^"]+)"[^>]*>', html):
                        articles.append({"url": "https://www.cnn.com" + m.group(1), "title": ""})
                if articles:
                    data["articles"] = articles[:20]
                    data["article_count"] = len(articles)

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