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


class NPM:
    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 /package/express or /package/@scope/name
            if "package" in parts:
                idx = parts.index("package")
                pkg = "/".join(parts[idx+1:])
            else:
                pkg = parts[-1] if parts else ""
            if not pkg:
                return {"success": False, "data": {}, "source": "npm-registry", "error": "No package name"}
            resp = self.client.fetch(f"https://registry.npmjs.org/{pkg}/latest", timeout=10)
            if resp.status_code == 200:
                d = resp.json()
                return {"success": True, "data": {
                    "name": d.get("name"),
                    "version": d.get("version"),
                    "description": d.get("description"),
                    "homepage": d.get("homepage"),
                }, "source": "npm-registry", "error": None}
            return {"success": False, "data": {}, "source": "npm-registry", "error": f"HTTP {resp.status_code}"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "npm-registry", "error": str(e)}
