"""PyPI site preset."""
from urllib.parse import urlparse


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

    def extract(self, url):
        try:
            parts = [p for p in urlparse(url).path.strip("/").split("/") if p]
            # Handle /project/requests/ or /pypi/requests/json
            if "project" in parts:
                pkg = parts[parts.index("project") + 1]
            elif "pypi" in parts:
                pkg = parts[parts.index("pypi") + 1]
            else:
                pkg = parts[-1] if parts else ""
            if not pkg:
                return {"success": False, "data": {}, "source": "pypi-api", "error": "No package name"}
            resp = self.client.fetch(f"https://pypi.org/pypi/{pkg}/json", timeout=10)
            if resp.status_code == 200:
                d = resp.json().get("info", {})
                return {"success": True, "data": {
                    "name": d.get("name"),
                    "version": d.get("version"),
                    "summary": d.get("summary"),
                    "author": d.get("author"),
                    "home_page": d.get("home_page"),
                }, "source": "pypi-api", "error": None}
            return {"success": False, "data": {}, "source": "pypi-api", "error": f"HTTP {resp.status_code}"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "pypi-api", "error": str(e)}
