"""
AkDevz AI Market Intelligence — Trade Candidate Generator
Generates concrete trade candidates (BUY CE, BUY PE, WAIT, NO TRADE)
from quantitative strategy evaluation and option strike selection.
"""
from typing import Dict, Any, List, Optional
from python.intelligence.risk_engine import RiskEngine

class CandidateGenerator:
    @staticmethod
    def generate_candidates(
        symbol: str,
        ltp: float,
        strategy_candidates: List[Dict[str, Any]],
        regime: str,
        pivots: Dict[str, float],
        lot_size: int = 25
    ) -> List[Dict[str, Any]]:
        """
        Synthesizes validated candidate setups from matched quantitative strategies.
        """
        if not strategy_candidates:
            return [{
                "candidate_type": "NO_TRADE",
                "bias": "NEUTRAL",
                "setup_name": "NO_QUANT_CONFLUENCE",
                "symbol": symbol,
                "contract_symbol": None,
                "entry_trigger": "Wait for a confirmed structural breakout or pullback.",
                "entry_price": ltp,
                "stop_loss": None,
                "target_1": None,
                "target_2": None,
                "reward_to_risk": 0.0,
                "why_take": [],
                "why_avoid": ["No strategy met the required mathematical threshold."],
                "invalidation": "N/A"
            }]

        results = []
        for strat in strategy_candidates:
            strat_name = strat.get("strategy", "UNKNOWN")
            bias = strat.get("bias", "NEUTRAL")
            entry_type = strat.get("entry_type", "WAIT")
            entry_trigger = strat.get("trigger", f"Price confirmation at {ltp}")
            sl = float(strat.get("stop_loss", ltp * 0.99))
            t1 = float(strat.get("target_1", ltp * 1.015))
            t2 = float(strat.get("target_2", ltp * 1.025))

            # Compute risk/reward
            rr_data = RiskEngine.calculate_rr(
                entry_price=ltp,
                stop_loss=sl,
                target_price=t1,
                lot_size=lot_size,
                slippage_pts=1.5
            )

            # Option candidate designation
            opt_type = "CE" if "BULLISH" in bias else ("PE" if "BEARISH" in bias else "NONE")
            contract_sym = f"{symbol}-{opt_type}-ATM" if opt_type != "NONE" else None

            results.append({
                "candidate_type": f"BUY_{opt_type}" if opt_type != "NONE" else "WAIT",
                "bias": bias,
                "setup_name": strat_name,
                "symbol": symbol,
                "contract_symbol": contract_sym,
                "entry_trigger": entry_trigger,
                "entry_price": round(ltp, 2),
                "stop_loss": round(sl, 2),
                "target_1": round(t1, 2),
                "target_2": round(t2, 2),
                "reward_to_risk": rr_data["reward_to_risk_ratio"],
                "net_rr": rr_data["net_rr"],
                "net_pnl_target": rr_data["net_profit_target"],
                "net_loss_stop": rr_data["net_loss_stop"],
                "costs": rr_data["total_estimated_costs"],
                "why_take": strat.get("confirmations", []),
                "why_avoid": strat.get("risks", []),
                "invalidation": f"Price crosses opposite invalidation level at {sl:.2f}"
            })

        return results
