"""
AkDevz AI Market Intelligence — Unified FYERS Client
Coordinates REST client, Rate Limiter, Auth verification, and Capabilities.
"""
from typing import Dict, Any, List, Optional
from python.config.settings import settings
from python.fyers.auth import FyersAuth
from python.fyers.rest_client import FyersRestClient
from python.fyers.rate_limiter import rate_limiter, FyersRateLimiter
from python.fyers.capabilities import FyersCapabilities
from python.fyers.instrument_master import InstrumentMaster

class FyersClient:
    """
    Unified FYERS V3 Client providing authenticated access to data feeds.
    Strictly analysis-only: order execution methods are forbidden.
    """

    def __init__(self, app_id: Optional[str] = None, access_token: Optional[str] = None):
        self.app_id = app_id or settings.fyers_app_id
        self.access_token = access_token or ""
        self.rest = FyersRestClient(app_id=self.app_id, access_token=self.access_token)
        self.rate_limiter = rate_limiter
        self.capabilities = FyersCapabilities()
        self.instrument_master = InstrumentMaster()

    def set_access_token(self, token: str):
        self.access_token = token
        self.rest.access_token = token

    def is_authenticated(self) -> bool:
        return bool(self.access_token and len(self.access_token) > 10)

    def test_connection(self) -> Dict[str, Any]:
        """Validates API token against /api/v3/profile."""
        if not self.is_authenticated():
            return {
                "success": False,
                "status": "UNAUTHENTICATED",
                "message": "FYERS Access Token is missing or empty. Please authenticate via Settings.",
                "profile": None
            }
        try:
            profile = self.rest.get_profile()
            return {
                "success": True,
                "status": "CONNECTED",
                "message": "Successfully authenticated with FYERS API V3.",
                "profile": profile
            }
        except Exception as e:
            return {
                "success": False,
                "status": "ERROR",
                "message": f"Connection test failed: {str(e)}",
                "profile": None
            }

    def get_quotes(self, symbols: List[str]) -> Dict[str, Any]:
        return self.rest.get_quotes(symbols)

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

    def get_option_chain(self, symbol: str, strike_count: int = 15, expiry: str = "") -> Dict[str, Any]:
        return self.rest.get_option_chain(symbol, strike_count=strike_count, expiry=expiry)

    def get_market_depth(self, symbol: str) -> Dict[str, Any]:
        return self.rest.get_market_depth(symbol)

    def get_rate_limit_stats(self) -> Dict[str, Any]:
        return self.rate_limiter.get_stats()
