"""Predefined learning courses for trading agents.

Each course provides specific skill improvements and may unlock
trading factors upon completion.
"""

from openclaw.learning.models import Course, SkillEffect, SkillType


def create_technical_analysis_course() -> Course:
    """Technical analysis course - improves market analysis skills.

    Teaches agents how to read charts, identify patterns, and
    understand technical indicators for better trading decisions.

    Returns:
        Course instance
    """
    return Course(
        course_id="technical_analysis_101",
        name="Technical Analysis Fundamentals",
        description=(
            "Learn to interpret price charts, identify support/resistance levels, "
            "recognize common chart patterns (head and shoulders, triangles, flags), "
            "and understand volume analysis. Foundation for systematic trading."
        ),
        duration_days=7,
        cost=500.0,
        prerequisites={},  # No prerequisites - beginner course
        effects=[
            SkillEffect(
                skill_type=SkillType.ANALYSIS,
                improvement=0.15,  # +15% analysis skill
                unlocks_factors=["trend_following", "support_resistance"],
            ),
        ],
    )


def create_risk_management_course() -> Course:
    """Risk management course - improves risk control skills.

    Teaches position sizing, stop-loss strategies, portfolio
    diversification, and capital preservation techniques.

    Returns:
        Course instance
    """
    return Course(
        course_id="risk_management_101",
        name="Risk Management Essentials",
        description=(
            "Master the art of protecting capital. Learn position sizing formulas, "
            "optimal stop-loss placement, risk/reward ratios, correlation analysis, "
            "and portfolio-level risk control. Essential for survival."
        ),
        duration_days=5,
        cost=750.0,
        prerequisites={},  # No prerequisites - essential for all
        effects=[
            SkillEffect(
                skill_type=SkillType.RISK_MANAGEMENT,
                improvement=0.20,  # +20% risk management skill
                unlocks_factors=["position_sizing", "stop_loss_optimization"],
            ),
        ],
    )


def create_market_psychology_course() -> Course:
    """Market psychology course - improves sentiment analysis.

    Teaches understanding of market sentiment, fear/greed cycles,
    contrarian indicators, and emotional discipline.

    Returns:
        Course instance
    """
    return Course(
        course_id="market_psychology_101",
        name="Market Psychology & Sentiment",
        description=(
            "Understand the emotional drivers of market movements. Learn to read "
            "fear and greed indicators, recognize bubble psychology, identify "
            "capitulation signals, and develop emotional discipline in trading."
        ),
        duration_days=10,
        cost=1000.0,
        prerequisites={
            SkillType.ANALYSIS: 0.3,  # Need some analysis skill first
        },
        effects=[
            SkillEffect(
                skill_type=SkillType.PSYCHOLOGY,
                improvement=0.25,  # +25% psychology skill
                unlocks_factors=["sentiment_analysis", "fear_greed_index"],
            ),
        ],
    )


def create_advanced_strategy_course() -> Course:
    """Advanced strategy course - unlocks sophisticated techniques.

    Teaches multi-factor strategies, statistical arbitrage,
    machine learning signals, and portfolio construction.

    Returns:
        Course instance
    """
    return Course(
        course_id="advanced_strategies_101",
        name="Advanced Trading Strategies",
        description=(
            "Master sophisticated trading approaches. Learn multi-factor model "
            "construction, statistical arbitrage techniques, regime detection, "
            "cross-asset correlation trading, and advanced portfolio optimization."
        ),
        duration_days=14,
        cost=2000.0,
        prerequisites={
            SkillType.ANALYSIS: 0.5,
            SkillType.RISK_MANAGEMENT: 0.4,
        },
        effects=[
            SkillEffect(
                skill_type=SkillType.STRATEGY,
                improvement=0.30,  # +30% strategy skill
                unlocks_factors=[
                    "multi_factor_models",
                    "statistical_arbitrage",
                    "regime_detection",
                    "momentum_factors",
                    "mean_reversion",
                ],
            ),
        ],
    )


# Convenience instances for direct use
TechnicalAnalysisCourse = create_technical_analysis_course()
RiskManagementCourse = create_risk_management_course()
MarketPsychologyCourse = create_market_psychology_course()
AdvancedStrategyCourse = create_advanced_strategy_course()


# Registry of all available courses
ALL_COURSES: list[Course] = [
    TechnicalAnalysisCourse,
    RiskManagementCourse,
    MarketPsychologyCourse,
    AdvancedStrategyCourse,
]


def get_course_by_id(course_id: str) -> Course | None:
    """Get a course by its ID.

    Args:
        course_id: The course identifier

    Returns:
        Course instance or None if not found
    """
    for course in ALL_COURSES:
        if course.course_id == course_id:
            return course
    return None


def get_available_courses(
    skill_levels: dict[SkillType, float],
    completed_courses: list[str],
) -> list[Course]:
    """Get list of courses the agent can enroll in.

    Args:
        skill_levels: Current skill levels
        completed_courses: List of completed course IDs

    Returns:
        List of courses that can be enrolled in
    """
    available = []
    for course in ALL_COURSES:
        # Skip completed courses
        if course.course_id in completed_courses:
            continue
        # Check prerequisites
        if course.can_enroll(skill_levels):
            available.append(course)
    return available
