"""
AkDevz AI Market Intelligence — Option Liquidity & Execution Risk Engine
Evaluates contract bid-ask spreads, Open Interest, Volume, and slippage viability.
"""
from typing import Dict, Any

class LiquidityEngine:
    @staticmethod
    def evaluate_contract_liquidity(
        bid: float,
        ask: float,
        oi: int,
        volume: int,
        min_oi: int = 50000,
        min_vol: int = 10000,
        max_spread_pct: float = 3.0
    ) -> Dict[str, Any]:
        """
        Determines if an option strike is safe for execution or has high slippage risk.
        """
        if ask <= 0 or bid <= 0:
            return {
                "is_liquid": False,
                "liquidity_score": 0.0,
                "spread_pct": 100.0,
                "reason": "Missing bid or ask prices. Zero liquidity detected."
            }

        spread = ask - bid
        mid = (ask + bid) / 2.0
        spread_pct = (spread / mid) * 100.0 if mid > 0 else 100.0

        penalties = 0.0
        reasons = []

        # Spread evaluation
        if spread_pct > max_spread_pct:
            penalties += 40.0
            reasons.append(f"Spread of {spread_pct:.2f}% exceeds safety threshold of {max_spread_pct:.1f}%.")
        elif spread_pct > 1.5:
            penalties += 15.0

        # OI evaluation
        if oi < min_oi:
            penalties += 30.0
            reasons.append(f"Open Interest ({oi:,}) is below required minimum ({min_oi:,}).")
        elif oi < min_oi * 2:
            penalties += 10.0

        # Volume evaluation
        if volume < min_vol:
            penalties += 30.0
            reasons.append(f"Intraday volume ({volume:,}) is below required minimum ({min_vol:,}).")
        elif volume < min_vol * 2:
            penalties += 10.0

        score = max(0.0, 100.0 - penalties)
        is_liquid = (score >= 60.0) and (spread_pct <= max_spread_pct)

        return {
            "is_liquid": is_liquid,
            "liquidity_score": round(score, 1),
            "spread_pct": round(spread_pct, 2),
            "spread_points": round(spread, 2),
            "oi": oi,
            "volume": volume,
            "reasons": reasons,
            "status": "APPROVED" if is_liquid else "REJECTED_ILLIQUID"
        }
