"""
AkDevz AI Market Intelligence — Market Depth (Level 2) Engine
Analyzes order book depth, bid/ask quantities, imbalance ratios, and absorption proxies.
"""
from typing import Dict, Any, Optional
from python.fyers.rest_client import FyersRestClient

class MarketDepthEngine:
    def __init__(self, rest_client: Optional[FyersRestClient] = None):
        self.client = rest_client or FyersRestClient()

    def analyze_depth(self, symbol: str) -> Dict[str, Any]:
        """
        Fetches Level-2 market depth from FYERS and analyzes order book dynamics.
        """
        try:
            depth_data = self.client.get_market_depth(symbol)
        except Exception as e:
            return {
                "symbol": symbol,
                "status": "ERROR",
                "message": str(e),
                "imbalance_ratio": 1.0,
                "bias": "UNCERTAIN"
            }

        d = depth_data.get("d", {}).get(symbol, {})
        bids = d.get("bids", [])
        asks = d.get("ask", [])
        total_buy_qty = d.get("totalbuyqty", 0)
        total_sell_qty = d.get("totalsellqty", 0)

        # Imbalance calculation
        total_qty = total_buy_qty + total_sell_qty
        buy_pressure_pct = (total_buy_qty / total_qty * 100.0) if total_qty > 0 else 50.0
        imbalance_ratio = (total_buy_qty / total_sell_qty) if total_sell_qty > 0 else 1.0

        spread = 0.0
        spread_pct = 0.0
        best_bid = float(bids[0]["price"]) if bids and len(bids) > 0 else 0.0
        best_ask = float(asks[0]["price"]) if asks and len(asks) > 0 else 0.0

        if best_bid > 0 and best_ask > 0:
            spread = max(0.0, best_ask - best_bid)
            spread_pct = (spread / best_ask) * 100.0

        # Liquidity absorption proxy
        absorption_hypothesis = "NORMAL_LIQUIDITY"
        if imbalance_ratio > 2.0 and spread_pct < 0.1:
            absorption_hypothesis = "HEAVY_BID_ACCUMULATION_PROXY"
        elif imbalance_ratio < 0.5 and spread_pct < 0.1:
            absorption_hypothesis = "HEAVY_ASK_DISTRIBUTION_PROXY"
        elif spread_pct > 0.5:
            absorption_hypothesis = "THIN_LIQUIDITY_WIDE_SPREAD"

        return {
            "symbol": symbol,
            "status": "VALID",
            "best_bid": best_bid,
            "best_ask": best_ask,
            "spread": round(spread, 2),
            "spread_pct": round(spread_pct, 3),
            "total_buy_qty": total_buy_qty,
            "total_sell_qty": total_sell_qty,
            "buy_pressure_pct": round(buy_pressure_pct, 1),
            "imbalance_ratio": round(imbalance_ratio, 2),
            "absorption_hypothesis": absorption_hypothesis,
            "bids_depth": bids[:5],
            "asks_depth": asks[:5]
        }
