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


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

    def extract(self, url):
        try:
            parts = [p for p in urlparse(url).path.strip("/").split("/") if p]
            coin = parts[-1] if parts else "bitcoin"
            resp = self.client.fetch(f"https://api.coingecko.com/api/v3/simple/price?ids={coin}&vs_currencies=usd", timeout=10)
            if resp.status_code == 200:
                d = resp.json()
                if coin in d:
                    return {"success": True, "data": {
                        "coin": coin,
                        "price_usd": d[coin].get("usd"),
                    }, "source": "coingecko-api", "error": None}
            return {"success": False, "data": {}, "source": "coingecko-api", "error": "Coin not found"}
        except Exception as e:
            return {"success": False, "data": {}, "source": "coingecko-api", "error": str(e)}
