"""
AkDevz AI Market Intelligence — Paper Outcome Tracker
Tracks immutable hypothetical trade decisions, validating trigger events,
MFE (Max Favorable Excursion), MAE (Max Adverse Excursion), stops, and targets.
"""
from typing import Dict, Any, List, Optional
import time

class PaperOutcomeTracker:
    @staticmethod
    def evaluate_setup_outcome(
        setup: Dict[str, Any],
        subsequent_candles: List[Dict[str, Any]],
        slippage_pts: float = 1.5,
        lot_size: int = 25
    ) -> Dict[str, Any]:
        """
        Evaluates an immutable hypothetical trade setup against subsequent price action:
        Outcomes:
        - TARGET_REACHED
        - STOP_REACHED
        - INVALIDATED_BEFORE_ENTRY
        - NEVER_TRIGGERED
        - EXPIRED
        """
        entry_trigger = float(setup.get("entry_price", 0.0))
        stop_loss = float(setup.get("stop_loss", 0.0))
        target_1 = float(setup.get("target_1", 0.0))
        target_2 = float(setup.get("target_2", 0.0))
        direction = "BUY" if "CE" in setup.get("candidate_type", "BUY_CE") else "SELL"

        if not subsequent_candles:
            return {
                "setup_id": setup.get("id"),
                "status": "WAITING_FOR_DATA",
                "triggered": False,
                "outcome": "UNRESOLVED",
                "mfe_pts": 0.0,
                "mae_pts": 0.0,
                "final_pnl": 0.0
            }

        triggered = False
        trigger_index = -1
        fill_price = 0.0

        # Step 1: Detect if and when entry trigger occurred
        for idx, bar in enumerate(subsequent_candles):
            h = float(bar["high"])
            l = float(bar["low"])

            if direction == "BUY" and h >= entry_trigger:
                triggered = True
                trigger_index = idx
                fill_price = entry_trigger + slippage_pts
                break
            elif direction == "SELL" and l <= entry_trigger:
                triggered = True
                trigger_index = idx
                fill_price = entry_trigger - slippage_pts
                break

        if not triggered:
            return {
                "setup_id": setup.get("id"),
                "status": "COMPLETED",
                "triggered": False,
                "outcome": "NEVER_TRIGGERED",
                "mfe_pts": 0.0,
                "mae_pts": 0.0,
                "final_pnl": 0.0,
                "message": "Entry condition was never met during the session. Counted as neutral, not a loss."
            }

        # Step 2: Track post-trigger path for Stop vs Target
        trade_high = fill_price
        trade_low = fill_price
        outcome = "UNRESOLVED"
        exit_price = 0.0

        for bar in subsequent_candles[trigger_index:]:
            h = float(bar["high"])
            l = float(bar["low"])

            trade_high = max(trade_high, h)
            trade_low = min(trade_low, l)

            if direction == "BUY":
                if l <= stop_loss:
                    outcome = "STOP_REACHED"
                    exit_price = stop_loss - slippage_pts
                    break
                elif h >= target_1:
                    outcome = "TARGET_REACHED"
                    exit_price = target_1 - slippage_pts
                    break
            else:  # SELL
                if h >= stop_loss:
                    outcome = "STOP_REACHED"
                    exit_price = stop_loss + slippage_pts
                    break
                elif l <= target_1:
                    outcome = "TARGET_REACHED"
                    exit_price = target_1 + slippage_pts
                    break

        if outcome == "UNRESOLVED":
            # Session expired with open position
            outcome = "SESSION_EXPIRED"
            last_close = float(subsequent_candles[-1]["close"])
            exit_price = last_close

        mfe = (trade_high - fill_price) if direction == "BUY" else (fill_price - trade_low)
        mae = (fill_price - trade_low) if direction == "BUY" else (trade_high - fill_price)

        pts = (exit_price - fill_price) if direction == "BUY" else (fill_price - exit_price)
        final_pnl = pts * lot_size

        return {
            "setup_id": setup.get("id"),
            "status": "COMPLETED",
            "triggered": True,
            "outcome": outcome,
            "fill_price": round(fill_price, 2),
            "exit_price": round(exit_price, 2),
            "mfe_pts": round(mfe, 2),
            "mae_pts": round(mae, 2),
            "final_pnl": round(final_pnl, 2),
            "is_profitable": final_pnl > 0
        }
