"""EDIT POINT: Angel One SmartAPI adapter for NIFTY 50, India VIX and NIFTY CE/PE.

Only this file should know Angel One request fields/token master mapping. Do not put
TOTP, PIN, or API keys in this file; they belong in `.env`.
"""
from datetime import datetime, timezone
import pyotp
from app.core.settings import get_settings
from app.sources.contracts import Quote


class AngelOneSource:
    def _client(self):
        settings = get_settings()
        if not all([settings.angel_api_key, settings.angel_client_code, settings.angel_pin, settings.angel_totp_secret]):
            raise RuntimeError("Angel One credentials are missing; set them in .env")
        # EDIT POINT: keep SmartAPI authentication/token refresh only in this adapter.
        from SmartApi import SmartConnect
        client = SmartConnect(api_key=settings.angel_api_key)
        session = client.generateSession(settings.angel_client_code, settings.angel_pin, pyotp.TOTP(settings.angel_totp_secret).now())
        if not session.get("status"):
            raise RuntimeError(f"Angel One login failed: {session}")
        return client

    def latest(self, symbol: str) -> Quote:
        # EDIT POINT: mappings stay in .env so replacing tokens cannot affect other modules.
        instrument = get_settings().angel_instrument(symbol)
        payload = self._client().ltpData(instrument["exchange"], instrument["tradingsymbol"], instrument["symboltoken"])
        if not payload.get("status"):
            raise RuntimeError(f"Angel quote request failed: {payload}")
        data = payload["data"]
        return Quote("angel_one", symbol, datetime.now(timezone.utc), float(data["ltp"]), open=data.get("open"), high=data.get("high"), low=data.get("low"), close=data.get("close"), raw=payload)

    def nifty_option_chain(self, expiry: str, strike: int) -> list[Quote]:
        """Use scrip-master token mappings for CE/PE; wire full-mode WebSocket snapshots here."""
        raise NotImplementedError("Option-chain streaming requires expiry-specific CE/PE token discovery.")
