from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import List, Optional

from app.services.openrouter import openrouter_service
from app.schemas.schemas import (
    AIAnalysisRequest,
    AIAnalysisResponse,
    AIPlanGenerationRequest,
    AIPlanGenerationResponse,
    AIPlanFeedback
)
from app.services.decisions import log_decision
from app.services.ai_plan_service import ai_plan_service
from app.db.database import get_db

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


@router.post("/analyze", response_model=AIAnalysisResponse)
async def analyze_scenario(request: AIAnalysisRequest):
    """
    Analyze trading scenario using AI (Claude 3.5 Sonnet via OpenRouter)

    Provides:
    - Trading recommendation (BUY/SELL/HOLD)
    - Confidence level
    - Detailed reasoning
    - Support and resistance levels
    - Risk assessment
    """
    try:
        analysis = await openrouter_service.analyze_scenario(request)
        # Log decision (best-effort) with minimal metadata
        try:
            log_decision(
                symbol="XAU/USD",
                timeframe="unknown",
                style="unknown",
                recommendation=analysis.recommendation.value if hasattr(analysis, 'recommendation') else str(analysis.recommendation),
                confidence=float(analysis.confidence),
                risk_level=analysis.risk_level.value if hasattr(analysis, 'risk_level') else str(analysis.risk_level),
                rationale=analysis.reasoning,
                inputs_hash=None,
                cost={},
            )
        except Exception:
            pass
        return analysis

    except Exception as e:
        raise HTTPException(
            status_code=500, detail=f"AI analysis failed: {str(e)}"
        )


@router.post("/generate-plan", response_model=AIPlanGenerationResponse)
async def generate_trading_plan(
    request: AIPlanGenerationRequest,
    user_id: Optional[str] = None,
    db: Session = Depends(get_db)
):
    """
    Generate a comprehensive daily trading plan using AI
    
    Uses user's indicator preferences and market data to create:
    - Market bias (BULLISH/BEARISH/NEUTRAL)
    - Entry zones and targets
    - Support and resistance levels
    - Risk management parameters
    - Trading strategy notes
    """
    try:
        plan = await ai_plan_service.generate_plan(db, request, user_id)
        return plan
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"AI plan generation failed: {str(e)}"
        )


@router.get("/plans/history", response_model=List[AIPlanGenerationResponse])
async def get_plan_history(
    user_id: Optional[str] = None,
    limit: int = 10,
    db: Session = Depends(get_db)
):
    """Get historical AI-generated trading plans"""
    try:
        plans = await ai_plan_service.get_plan_history(db, user_id, limit)
        return plans
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to fetch plan history: {str(e)}"
        )


@router.post("/plans/feedback")
async def submit_plan_feedback(
    feedback: AIPlanFeedback,
    db: Session = Depends(get_db)
):
    """Submit feedback on an AI-generated plan"""
    try:
        plan = await ai_plan_service.submit_feedback(
            db,
            feedback.plan_id,
            feedback.accepted,
            feedback.modified,
            feedback.feedback
        )
        return {"success": True, "message": "Feedback submitted successfully"}
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to submit feedback: {str(e)}"
        )
