"""Shopify store preset — works with any Shopify store via /products.json API."""
from urllib.parse import urlparse


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

    @staticmethod
    def is_shopify(url):
        """Check if a URL is a Shopify store by trying /products.json."""
        try:
            parsed = urlparse(url)
            base = f"{parsed.scheme}://{parsed.netloc}"
            resp = self.client.fetch(f"{base}/products.json?limit=1", timeout=8,
                                headers={"User-Agent": "Mozilla/5.0"})
            return resp.status_code == 200 and "products" in resp.text[:100]
        except Exception:
            return False

    def extract(self, url):
        try:
            parsed = urlparse(url)
            base = f"{parsed.scheme}://{parsed.netloc}"
            headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

            # Fetch products
            resp = self.client.fetch(f"{base}/products.json?limit=30", headers=headers, timeout=15)
            if resp.status_code != 200:
                return {"success": False, "data": {}, "source": "shopify-api", "error": f"HTTP {resp.status_code}"}

            raw = resp.json()
            products = []
            for p in raw.get("products", []):
                variant = p.get("variants", [{}])[0] if p.get("variants") else {}
                products.append({
                    "title": p.get("title", ""),
                    "price": variant.get("price", ""),
                    "vendor": p.get("vendor", ""),
                    "product_type": p.get("product_type", ""),
                    "handle": p.get("handle", ""),
                })

            data = {"products": products, "count": len(products), "store": parsed.netloc}

            # Try collections too
            try:
                cr = self.client.fetch(f"{base}/collections.json", headers=headers, timeout=8)
                if cr.status_code == 200:
                    cols = cr.json().get("collections", [])
                    data["collections"] = [{"title": c.get("title", ""), "handle": c.get("handle", "")} for c in cols[:10]]
            except Exception:
                pass

            return {"success": len(products) > 0, "data": data, "source": "shopify-api", "error": None}
        except Exception as e:
            return {"success": False, "data": {}, "source": "shopify-api", "error": str(e)}
