"""
=========================================
CV6 AI Trading OS
AI Consensus Router
=========================================
"""

from typing import Optional, Dict, Any
from fastapi import APIRouter
from pydantic import BaseModel, Field

from app.ai.ai_consensus import consensus_engine, ConsensusResult

router = APIRouter(
    prefix="/ai/consensus",
    tags=["AI Consensus"],
)


class ConsensusRequest(BaseModel):
    symbol:  str = Field(..., example="NIFTY")
    context: Optional[str] = None       # extra context from frontend
    ltp:     Optional[float] = Field(None, example=23542.5)
    open:    Optional[float] = None
    high:    Optional[float] = None
    low:     Optional[float] = None
    close:   Optional[float] = None
    volume:  Optional[int]   = None
    rsi:     Optional[float] = Field(None, example=58.4)
    macd:    Optional[float] = None
    ema:     Optional[str]   = Field(None, example="BULLISH")
    trend:   Optional[str]   = Field(None, example="UP")
    change_pct: Optional[float] = None


@router.post(
    "/analyze",
    summary="Run AI consensus across all active models",
    response_description="Consensus signal with per-model breakdown",
)
async def run_consensus(request: ConsensusRequest):
    """
    Runs GPT, Claude, DeepSeek, Gemini, Llama (Groq), Ollama in parallel.
    Returns weighted majority BUY / SELL / HOLD with confidence % and reason.
    """
    data = request.model_dump(exclude_none=True)
    symbol = data.pop("symbol")
    data.pop("context", None)   # not a market data field
    result = await consensus_engine.consensus(symbol=symbol, market_data=data)
    d = result.to_dict()
    # Return both legacy and normalised field names for compatibility
    return {
        "success":    True,
        "result":     d,
        "consensus":  d.get("signal", "HOLD"),
        "confidence": d.get("confidence", 0),
        "reason":     d.get("reason", ""),
        "signals":    [
            {
                "model":      m.get("model"),
                "signal":     m.get("signal", "HOLD"),
                "confidence": round(m.get("confidence", 0) * 100, 1) if m.get("confidence", 0) <= 1 else round(m.get("confidence", 0), 1),
                "reason":     m.get("reason", ""),
                "latency_ms": m.get("latency_ms", 0),
                "error":      m.get("error"),
            }
            for m in d.get("models", [])
        ],
        "symbol": symbol,
    }


@router.get(
    "/models",
    summary="List active AI models in the consensus engine",
)
def list_models():
    """Returns which AI models are active."""
    return {
        "success": True,
        "models": [a.name for a in consensus_engine.adapters],
        "total":  len(consensus_engine.adapters),
    }
