"""
Trading Schools API
Endpoints for accessing trading methodologies, strategies, and plan templates
"""

from fastapi import APIRouter, Query, HTTPException
from typing import Optional, List
from pydantic import BaseModel

from app.services.trading_schools import trading_schools, TradingSchool
from app.services.plan_templates import plan_templates, PlanType, MarketCondition


router = APIRouter(prefix="/api/trading-schools", tags=["Trading Schools"])


# Pydantic Models
class TradingSchoolInfo(BaseModel):
    """Trading school information"""
    school: str
    name: str
    description: str
    key_concepts: List[str]
    timeframes: List[str]
    indicators: List[str]
    best_for: List[str]


class GeneratePlanRequest(BaseModel):
    """Request to generate a trading plan"""
    methodology: str  # ict_smc, wyckoff, multi_confluence, etc.
    current_price: float
    market_condition: Optional[str] = "trending_up"
    session: Optional[str] = "london_ny"
    risk_tolerance: Optional[str] = "moderate"


# ============================================================================
# TRADING SCHOOLS ENDPOINTS
# ============================================================================

@router.get("/list")
async def get_all_trading_schools():
    """Get list of all available trading schools and methodologies"""
    schools = trading_schools.get_all_schools()

    return {
        "total_schools": len(schools),
        "schools": list(schools.keys()),
        "schools_detail": schools,
        "description": "Comprehensive collection of trading methodologies"
    }


@router.get("/school/{school_name}")
async def get_school_details(school_name: str):
    """Get detailed information about a specific trading school"""
    schools = trading_schools.get_all_schools()

    if school_name not in schools:
        raise HTTPException(
            status_code=404,
            detail=f"School '{school_name}' not found. Available schools: {list(schools.keys())}"
        )

    return schools[school_name]


@router.get("/combined-strategies")
async def get_combined_strategies():
    """Get hybrid strategies combining multiple trading schools"""
    strategies = trading_schools.get_combined_strategies()

    return {
        "total_strategies": len(strategies),
        "strategies": strategies,
        "description": "Hybrid approaches combining multiple methodologies for higher probability setups"
    }


@router.get("/indicator-presets")
async def get_indicator_presets(school: Optional[str] = Query(None)):
    """Get recommended indicator configurations for trading schools"""
    if school:
        preset = trading_schools.get_indicator_presets_for_school(TradingSchool(school))
        return {
            "school": school,
            "preset": preset
        }

    # Get all presets
    all_presets = {}
    for s in TradingSchool:
        all_presets[s.value] = trading_schools.get_indicator_presets_for_school(s)

    return {
        "total_schools": len(all_presets),
        "presets": all_presets
    }


@router.get("/risk-models")
async def get_risk_management_models():
    """Get advanced risk management models and position sizing strategies"""
    models = trading_schools.get_risk_models()

    return {
        "total_models": len(models),
        "models": models,
        "recommendation": "Use Fixed Fractional (1-2% per trade) for beginners, Kelly Criterion for advanced traders with proven edge"
    }


# ============================================================================
# TRADING PLAN TEMPLATES ENDPOINTS
# ============================================================================

@router.get("/plan-types")
async def get_plan_types():
    """Get all available trading plan types"""
    types = plan_templates.get_all_plan_types()

    return {
        "total_types": len(types),
        "plan_types": types,
        "description": "Pre-built trading plan templates for different methodologies"
    }


@router.post("/generate-plan")
async def generate_trading_plan(request: GeneratePlanRequest):
    """
    Generate a comprehensive trading plan based on selected methodology

    Methodologies:
    - ict_smc: ICT / Smart Money Concepts
    - wyckoff: Wyckoff Method
    - multi_confluence: Multi-Method Confluence (ICT + Fib + S/D + PA)
    - session_trading: London/NY Session-Based Trading
    """
    try:
        # Validate market condition
        try:
            market_cond = MarketCondition(request.market_condition)
        except ValueError:
            market_cond = MarketCondition.TRENDING_UP

        # Generate plan based on methodology
        if request.methodology == "ict_smc":
            plan = plan_templates.generate_ict_smc_plan(
                current_price=request.current_price,
                market_condition=market_cond,
                session=request.session or "london_ny"
            )
        elif request.methodology == "wyckoff":
            plan = plan_templates.generate_wyckoff_plan(
                current_price=request.current_price,
                market_condition=market_cond
            )
        elif request.methodology == "multi_confluence":
            plan = plan_templates.generate_multi_method_confluence_plan(
                current_price=request.current_price,
                market_condition=market_cond
            )
        elif request.methodology == "session_trading":
            plan = plan_templates.generate_session_based_plan(
                current_price=request.current_price,
                target_session=request.session or "london_ny_overlap"
            )
        else:
            raise HTTPException(
                status_code=400,
                detail=f"Unknown methodology: {request.methodology}. Use: ict_smc, wyckoff, multi_confluence, or session_trading"
            )

        return {
            "methodology": request.methodology,
            "current_price": request.current_price,
            "market_condition": request.market_condition,
            "plan": plan,
            "generated_at": "now"
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/quick-reference/{school}")
async def get_quick_reference(school: str):
    """Get a quick reference guide for a specific trading school"""
    schools = trading_schools.get_all_schools()

    if school not in schools:
        raise HTTPException(status_code=404, detail=f"School '{school}' not found")

    school_data = schools[school]

    # Create quick reference
    quick_ref = {
        "name": school_data["name"],
        "school_type": school_data["school"],
        "elevator_pitch": school_data["description"],
        "key_concepts": school_data["key_concepts"][:5],  # Top 5
        "timeframes": school_data["timeframes"],
        "best_for": school_data["best_for"],
        "one_sentence_summary": _get_one_liner(school)
    }

    if "entry_criteria" in school_data:
        quick_ref["how_to_trade"] = school_data["entry_criteria"]

    if "risk_management" in school_data:
        quick_ref["risk_management"] = school_data["risk_management"]

    return quick_ref


@router.get("/comparison")
async def compare_trading_schools(
    schools_list: str = Query(..., description="Comma-separated list of schools to compare, e.g., ict_smc,wyckoff,price_action")
):
    """Compare multiple trading schools side by side"""
    school_names = [s.strip() for s in schools_list.split(",")]
    schools_data = trading_schools.get_all_schools()

    comparison = {}
    for school_name in school_names:
        if school_name not in schools_data:
            raise HTTPException(
                status_code=404,
                detail=f"School '{school_name}' not found"
            )

        data = schools_data[school_name]
        comparison[school_name] = {
            "name": data["name"],
            "description": data["description"],
            "timeframes": data["timeframes"],
            "indicators": data["indicators"],
            "best_for": data["best_for"],
            "complexity": _rate_complexity(school_name)
        }

    return {
        "schools_compared": len(comparison),
        "comparison": comparison,
        "recommendation": _get_comparison_recommendation(school_names)
    }


@router.get("/learning-path")
async def get_learning_path():
    """Get recommended learning path for mastering different trading schools"""
    return {
        "beginner_path": {
            "level": "Beginner (0-6 months)",
            "schools": [
                {
                    "order": 1,
                    "school": "price_action",
                    "name": "Price Action",
                    "reason": "Foundation - Learn to read candles and basic S/R",
                    "time_to_learn": "2-3 months"
                },
                {
                    "order": 2,
                    "school": "fibonacci_trading",
                    "name": "Fibonacci Trading",
                    "reason": "Simple tool, high applicability",
                    "time_to_learn": "1 month"
                },
                {
                    "order": 3,
                    "school": "supply_demand",
                    "name": "Supply & Demand Zones",
                    "reason": "Logical, builds on S/R knowledge",
                    "time_to_learn": "2 months"
                }
            ],
            "practice": "Demo trade minimum 3 months before real money"
        },
        "intermediate_path": {
            "level": "Intermediate (6-18 months)",
            "schools": [
                {
                    "order": 1,
                    "school": "ict_smc",
                    "name": "ICT / Smart Money Concepts",
                    "reason": "Modern, powerful for gold/forex",
                    "time_to_learn": "4-6 months"
                },
                {
                    "order": 2,
                    "school": "market_profile",
                    "name": "Market Profile",
                    "reason": "Understand volume and value",
                    "time_to_learn": "3 months"
                },
                {
                    "order": 3,
                    "school": "multi_timeframe",
                    "name": "Multi-Timeframe Analysis",
                    "reason": "Combine skills, improve timing",
                    "time_to_learn": "2 months"
                }
            ],
            "practice": "Start combining methods, track statistics"
        },
        "advanced_path": {
            "level": "Advanced (18+ months)",
            "schools": [
                {
                    "order": 1,
                    "school": "wyckoff",
                    "name": "Wyckoff Method",
                    "reason": "Deep market understanding, institutional perspective",
                    "time_to_learn": "6-12 months"
                },
                {
                    "order": 2,
                    "school": "elliott_wave",
                    "name": "Elliott Wave Theory",
                    "reason": "Complex but powerful for major moves",
                    "time_to_learn": "6-12 months"
                },
                {
                    "order": 3,
                    "school": "order_flow",
                    "name": "Order Flow Trading",
                    "reason": "Real-time institutional activity",
                    "time_to_learn": "3-6 months (requires specialized tools)"
                }
            ],
            "practice": "Develop personal methodology combining multiple schools"
        },
        "professional_edge": {
            "level": "Professional",
            "approach": "Multi-Method Confluence",
            "description": "Combine 3-4 methodologies for maximum probability setups",
            "schools": ["ict_smc", "fibonacci_trading", "supply_demand", "price_action"],
            "goal": "Trade only highest-quality setups with 70%+ win rate",
            "frequency": "1-3 trades per week (quality over quantity)"
        },
        "general_advice": [
            "Master ONE school completely before moving to next",
            "Journal every trade and study every setup",
            "Backtest each methodology on historical data",
            "Paper trade new methods for 2-3 months minimum",
            "Don't skip fundamentals (Price Action first!)",
            "Find 1-2 mentors for each major methodology",
            "Join communities: ICT students, Wyckoff traders, etc.",
            "Most profitable traders use 2-3 methods maximum (confluence)"
        ]
    }


# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

def _get_one_liner(school: str) -> str:
    """Get one-sentence summary of a trading school"""
    summaries = {
        "ict_smc": "Trade like institutions: Follow liquidity, FVGs, and order blocks during killzones.",
        "wyckoff": "Identify accumulation and distribution phases using volume to trade with smart money.",
        "elliott_wave": "Count wave structures and use Fibonacci to predict major market moves.",
        "market_profile": "Find value areas and trade price rejection from high/low volume nodes.",
        "order_flow": "Read real-time buying/selling pressure to anticipate institutional moves.",
        "price_action": "Trade pure price patterns at support/resistance without indicators.",
        "supply_demand": "Identify fresh zones of imbalance and trade rejections from these levels.",
        "fibonacci_trading": "Use golden ratio levels (0.618, 1.618) for entries and targets.",
        "gold_fundamental": "Trade gold based on USD strength, yields, inflation, and geopolitical factors.",
        "multi_timeframe": "Align multiple timeframes for high-probability entries with HTF targets.",
        "london_ny_session": "Trade gold during high-liquidity sessions (3-5 AM, 8-11 AM EST) for best moves."
    }
    return summaries.get(school, "A proven trading methodology.")


def _rate_complexity(school: str) -> str:
    """Rate the complexity of learning a trading school"""
    ratings = {
        "price_action": "Beginner",
        "fibonacci_trading": "Beginner",
        "supply_demand": "Beginner-Intermediate",
        "multi_timeframe": "Intermediate",
        "ict_smc": "Intermediate",
        "market_profile": "Intermediate-Advanced",
        "gold_fundamental": "Intermediate",
        "london_ny_session": "Intermediate",
        "wyckoff": "Advanced",
        "elliott_wave": "Advanced",
        "order_flow": "Advanced"
    }
    return ratings.get(school, "Intermediate")


def _get_comparison_recommendation(schools: List[str]) -> str:
    """Get recommendation based on schools being compared"""
    if len(schools) == 1:
        return f"Focus on mastering {schools[0]} before adding other methods."

    if "ict_smc" in schools and "fibonacci_trading" in schools and "supply_demand" in schools:
        return "Excellent combination! These three methods work very well together for confluence trading."

    if "wyckoff" in schools and any(s in schools for s in ["market_profile", "order_flow"]):
        return "Volume-based methods pair well. Focus on volume analysis across all methods."

    if len(schools) > 4:
        return "⚠️ Too many methods. Focus on mastering 2-3 maximum to avoid analysis paralysis."

    return "Good selection. Look for confluence zones where multiple methods confirm the same setup."
