"""Goodreads site preset."""
import re
import json


class Goodreads:
    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=15)
            html = resp.text
            data = {}
            # Try JSON-LD
            for m in re.finditer(r'<script type="application/ld\+json">(.*?)</script>', html, re.DOTALL):
                try:
                    ld = json.loads(m.group(1))
                    if ld.get("@type") == "Book" or "ratingValue" in str(ld):
                        data["title"] = ld.get("name")
                        author = ld.get("author")
                        if isinstance(author, list):
                            data["author"] = author[0].get("name") if author else None
                        elif isinstance(author, dict):
                            data["author"] = author.get("name")
                        ar = ld.get("aggregateRating", {})
                        data["rating"] = ar.get("ratingValue")
                        data["rating_count"] = ar.get("ratingCount")
                        break
                except json.JSONDecodeError:
                    continue
            if not data.get("title"):
                t = re.search(r'<title>([^<]+)</title>', html)
                if t:
                    data["title"] = t.group(1).strip()
            return {"success": bool(data.get("title")), "data": data, "source": "goodreads-http", "error": None}
        except Exception as e:
            return {"success": False, "data": {}, "source": "goodreads-http", "error": str(e)}
