"""Upstox REST quote adapter; intended for GIFT NIFTY."""
from datetime import datetime, timezone
import requests
from app.core.settings import get_settings
from app.sources.contracts import Quote


class UpstoxSource:
    URL = "https://api.upstox.com/v2/market-quote/quotes"

    def latest(self, symbol: str = "GIFT NIFTY") -> Quote:
        settings = get_settings()
        if not settings.upstox_access_token or not settings.upstox_gift_nifty_key:
            raise RuntimeError("Set UPSTOX_ACCESS_TOKEN and UPSTOX_GIFT_NIFTY_KEY in .env")
        response = requests.get(self.URL, params={"instrument_key": settings.upstox_gift_nifty_key}, headers={"Accept": "application/json", "Authorization": f"Bearer {settings.upstox_access_token}"}, timeout=15)
        response.raise_for_status()
        payload = response.json()
        # EDIT POINT: Upstox can revise response shapes; keep all payload mapping here.
        data = next(iter(payload["data"].values()))
        ohlc = data.get("ohlc", {})
        return Quote("upstox", symbol, datetime.now(timezone.utc), float(data["last_price"]), ohlc.get("open"), ohlc.get("high"), ohlc.get("low"), ohlc.get("close"), data.get("volume"), data.get("oi"), payload)
