"""Tiny cached USD->BTC price (free CoinGecko endpoint, no key)."""
import time, aiohttp, logging

log = logging.getLogger("genboost.price")
_CACHE: dict = {"ts": 0.0, "btc_usd": 0.0}
_TTL = 60.0
URL = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"


async def btc_usd() -> float:
    now = time.time()
    if _CACHE["btc_usd"] and now - _CACHE["ts"] < _TTL:
        return _CACHE["btc_usd"]
    try:
        async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as s:
            async with s.get(URL) as r:
                j = await r.json()
        price = float(j["bitcoin"]["usd"])
        if price > 0:
            _CACHE["btc_usd"] = price
            _CACHE["ts"] = now
            return price
    except Exception as e:
        log.warning("BTC price fetch failed: %s", e)
    # Fallback to last known value or a sane default so the bot keeps working.
    return _CACHE["btc_usd"] or 65000.0


async def usd_to_btc(usd: float) -> float:
    p = await btc_usd()
    return usd / p
