"""
AkDevz AI Market Intelligence — Upstox API v2 Broker Adapter
Supports OAuth2 authentication, market quotes, positions, and orders.
"""
import time
import logging
from typing import Dict, Any, List, Optional
from python.brokers.base_broker import BaseBrokerAdapter

logger = logging.getLogger(__name__)

class UpstoxBrokerAdapter(BaseBrokerAdapter):
    BASE_URL = "https://api.upstox.com/v2"

    def __init__(self, credentials: Dict[str, Any]):
        super().__init__("UPSTOX", credentials)
        self.api_key = credentials.get("client_id", "")
        self.api_secret = credentials.get("secret_key", "")
        self.access_token = credentials.get("access_token", "")

    def authenticate(self) -> bool:
        if self.access_token and len(self.access_token) > 20:
            self.is_authenticated = True
            return True
        return False

    def get_quotes(self, symbols: List[str]) -> Dict[str, Dict[str, Any]]:
        if not self.access_token:
            return {}
        import requests
        headers = {
            "Accept": "application/json",
            "Authorization": f"Bearer {self.access_token}"
        }
        # Upstox symbol format: e.g. NSE_EQ|INE002A01018 or NSE_INDEX|Nifty 50
        quotes = {}
        try:
            sym_keys = ",".join([s.replace("NSE:", "NSE_EQ|").replace("-EQ", "") for s in symbols[:20]])
            resp = requests.get(f"{self.BASE_URL}/market-quote/quotes?instrument_key={sym_keys}", headers=headers, timeout=8)
            if resp.status_code == 200:
                data = resp.json().get("data", {})
                for k, v in data.items():
                    quotes[k] = {
                        "symbol": k,
                        "ltp": float(v.get("last_price", 0.0)),
                        "open": float(v.get("ohlc", {}).get("open", 0.0)),
                        "high": float(v.get("ohlc", {}).get("high", 0.0)),
                        "low": float(v.get("ohlc", {}).get("low", 0.0)),
                        "close": float(v.get("ohlc", {}).get("close", 0.0)),
                        "volume": int(v.get("volume", 0)),
                        "timestamp": int(time.time()),
                        "provider": "UPSTOX"
                    }
        except Exception as e:
            logger.warning(f"Upstox quote error: {e}")
        return quotes

    def get_historical_candles(self, symbol: str, resolution: str = "5", range_from: str = "", range_to: str = "") -> List[List[Any]]:
        return []

    def get_option_chain(self, symbol: str, strike_count: int = 15) -> Optional[Dict[str, Any]]:
        return None

    def get_funds_and_margin(self) -> Dict[str, Any]:
        if not self.access_token:
            return {"available_funds": 0.0, "used_margin": 0.0, "status": "UNAUTHENTICATED"}
        import requests
        headers = {"Authorization": f"Bearer {self.access_token}", "Accept": "application/json"}
        try:
            resp = requests.get(f"{self.BASE_URL}/user/get-funds-and-margin", headers=headers, timeout=8)
            if resp.status_code == 200:
                eq = resp.json().get("data", {}).get("equity", {})
                return {
                    "available_funds": float(eq.get("available_margin", 0.0)),
                    "used_margin": float(eq.get("used_margin", 0.0)),
                    "status": "CONNECTED",
                    "provider": "UPSTOX"
                }
        except Exception:
            pass
        return {"available_funds": 0.0, "used_margin": 0.0, "status": "ERROR"}

    def get_positions(self) -> List[Dict[str, Any]]:
        if not self.access_token:
            return []
        import requests
        headers = {"Authorization": f"Bearer {self.access_token}", "Accept": "application/json"}
        try:
            resp = requests.get(f"{self.BASE_URL}/portfolio/short-term-positions", headers=headers, timeout=8)
            if resp.status_code == 200:
                return resp.json().get("data", []) or []
        except Exception:
            pass
        return []

    def place_order(self, order_params: Dict[str, Any]) -> Dict[str, Any]:
        if not self.access_token:
            return {"status": "error", "message": "Upstox token missing"}
        import requests
        headers = {"Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json"}
        try:
            resp = requests.post(f"{self.BASE_URL}/order/place", json=order_params, headers=headers, timeout=10)
            return resp.json()
        except Exception as e:
            return {"status": "error", "message": str(e)}

    def modify_order(self, order_id: str, params: Dict[str, Any]) -> Dict[str, Any]:
        return {"status": "error", "message": "Not implemented"}

    def cancel_order(self, order_id: str) -> Dict[str, Any]:
        return {"status": "error", "message": "Not implemented"}
