"""Wikipedia site preset."""
from urllib.parse import urlparse, unquote


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

    def extract(self, url):
        try:
            path = urlparse(url).path
            title = unquote(path.rstrip("/").split("/")[-1])
            resp = self.client.fetch(f"https://en.wikipedia.org/api/rest_v1/page/summary/{title}", timeout=10,
                                headers={"User-Agent": "IPLoopSDK/1.0 (https://iploop.io)"})
            if resp.status_code == 200:
                d = resp.json()
                return {"success": True, "data": {
                    "title": d.get("title"),
                    "extract": d.get("extract"),
                    "thumbnail": (d.get("thumbnail") or {}).get("source"),
                    "description": d.get("description"),
                }, "source": "wikipedia-api", "error": None}
            return {"success": False, "data": {}, "source": "wikipedia-api", "error": f"HTTP {resp.status_code}"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "wikipedia-api", "error": str(e)}
