"""
AkDevz AI Market Intelligence — Python Decision Gate
The final mathematical authority for approving BUY CE, BUY PE, WAIT, or NO TRADE.
"""
from typing import Dict, List, Any, Optional
from python.intelligence.risk_engine import RiskEngine

class DecisionGate:
    @staticmethod
    def evaluate_decision(
        symbol: str,
        regime_data: Dict[str, Any],
        candidates: List[Dict[str, Any]],
        data_freshness: str,
        data_age_sec: int,
        option_candidate: Optional[Dict[str, Any]] = None,
        lot_size: int = 25
    ) -> Dict[str, Any]:
        # Hard Gate 1: Stale or Incomplete Data
        if data_freshness in ["STALE", "OFF-MARKET"] or data_age_sec > 180:
            return {
                "decision": "WAIT",
                "market_bias": "UNCERTAIN",
                "setup_name": "NONE",
                "approved_candidate": None,
                "rejection_reasons": [
                    f"Market data is {data_freshness} (Age: {data_age_sec}s). Execution gate locked for capital safety."
                ],
                "why_wait": "Data freshness policy requires confirmed live observations (<60s) before any actionable setup can trigger.",
                "what_to_watch_next": "Wait for valid live market quote feed and session re-synchronization.",
                "python_validation": "LOCKED_STALE_DATA"
            }

        # Hard Gate 2: Choppy or Highly Uncertain Regime without tested setup
        regime = regime_data.get("regime", "UNCERTAIN")
        if regime in ["CHOPPY", "UNCERTAIN"] and not candidates:
            return {
                "decision": "NO_TRADE",
                "market_bias": "NEUTRAL",
                "setup_name": "NONE",
                "approved_candidate": None,
                "rejection_reasons": [
                    f"Market regime is {regime} (ADX < 18). High risk of whipsaws and premium decay."
                ],
                "why_wait": "Option buying in choppy sideways conditions suffers rapid theta decay and false breakout wicks.",
                "what_to_watch_next": "Watch for ADX expansion above 22 and sustained 15m candle close outside the morning range.",
                "python_validation": "REGIME_GUARD_ACTIVATED"
            }

        if not candidates:
            return {
                "decision": "WAIT",
                "market_bias": "NEUTRAL" if regime == "SIDEWAYS" else ("BULLISH" if "BULLISH" in regime else "BEARISH"),
                "setup_name": "NONE",
                "approved_candidate": None,
                "rejection_reasons": ["No mathematical strategy trigger currently satisfied."],
                "why_wait": "Waiting for objective setup confluence (VWAP, EMA alignment, and confirmed candle close).",
                "what_to_watch_next": "Monitor key levels for clean price-action rejection or volume expansion breakout.",
                "python_validation": "WAITING_FOR_TRIGGER"
            }

        # Hard Gate 3: Evaluate Candidates against Risk Engine & Option Liquidity
        for cand in candidates:
            entry = cand["trigger_price"]
            sl = cand["stop_loss"]
            t1 = cand["target_1"]

            risk_eval = RiskEngine.calculate_net_risk_reward(entry, sl, t1, lot_size=lot_size)
            if not risk_eval["is_acceptable"]:
                continue

            # Check Option Contract if attached
            if option_candidate:
                spread = float(option_candidate.get("spread_pct", 0.0))
                oi = int(option_candidate.get("oi", 0))
                if spread > 3.0:
                    continue  # Reject due to wide spread
                if oi < 50000:
                    continue  # Reject due to low open interest

            # Approved candidate
            cand["risk_metrics"] = risk_eval
            action = cand["action"]
            bias = "BULLISH" if action == "BUY_CE" else "BEARISH"

            return {
                "decision": action,
                "market_bias": bias,
                "setup_name": cand["strategy_name"],
                "approved_candidate": cand,
                "rejection_reasons": [],
                "why_wait": "Setup triggered with confirmed confluence. Manage risk at designated stop-loss.",
                "what_to_watch_next": f"Monitor reaction at Target 1 ({t1:.2f}) and protect capital if price violates Stop-Loss ({sl:.2f}).",
                "python_validation": "APPROVED"
            }

        # If all candidates failed risk/reward or liquidity
        return {
            "decision": "NO_TRADE",
            "market_bias": "UNCERTAIN",
            "setup_name": candidates[0]["strategy_name"] if candidates else "NONE",
            "approved_candidate": None,
            "rejection_reasons": [
                "Available candidate failed net reward-to-risk threshold (<1.5:1 after brokerage/slippage) or option spread was excessive."
            ],
            "why_wait": "Mathematical expectancy is negative after realistic execution costs. Capital preservation takes precedence.",
            "what_to_watch_next": "Wait for a deeper pullback that provides a tighter stop-loss and favorable risk/reward.",
            "python_validation": "FAILED_RISK_GATES"
        }
