"""Trustpilot site preset."""
import re
import json


class Trustpilot:
    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)
            if resp.status_code != 200:
                return {"success": False, "data": {}, "source": "trustpilot-http", "error": f"HTTP {resp.status_code}"}

            html = resp.text
            data = {}

            # Company name from title
            t = re.search(r'<title>([^<]*)</title>', html)
            if t:
                title = t.group(1).strip()
                # Format: "Company Reviews | Read ... | Trustpilot"
                data["company"] = title.split(" Reviews")[0].split("|")[0].strip()

            # Rating from JSON-LD
            rv = re.search(r'"ratingValue"\s*:\s*"?([0-9.]+)"?', html)
            if rv:
                data["rating"] = float(rv.group(1))

            # Review count
            rc = re.search(r'"reviewCount"\s*:\s*"?(\d+)"?', html)
            if rc:
                data["review_count"] = int(rc.group(1))

            # Sample reviews from JSON-LD
            reviews = []
            for m in re.finditer(r'"reviewBody"\s*:\s*"([^"]{10,300})"', html):
                reviews.append(m.group(1)[:200])
                if len(reviews) >= 5:
                    break
            if reviews:
                data["sample_reviews"] = reviews

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