"""
Strategy information endpoints.
"""
from typing import Any

import numpy as np
from fastapi import APIRouter

from api.models.schemas import StrategiesResponse, StrategyInfo
from strategies.factory import get_registry

router = APIRouter()


def _serialize_param_value(value: Any) -> Any:
    """Convert numpy arrays and other types to JSON-serializable format."""
    if isinstance(value, np.ndarray):
        return value.tolist()
    if isinstance(value, (np.integer, np.floating)):
        return value.item()
    return value


def _get_display_name(name: str) -> str:
    """Convert strategy key to display name."""
    display_names = {
        "rsi": "RSI Strategy",
        "macross": "MA Crossover",
        "meta_st": "Meta Supertrend",
        "regime": "Regime Reversion (ML)",
    }
    return display_names.get(name, name.replace("_", " ").title())


@router.get("/strategies", response_model=StrategiesResponse)
async def get_strategies():
    """
    Get list of available strategies with their parameters.
    
    Returns strategy names, default parameters, and grid search ranges.
    """
    registry = get_registry()
    strategies = []
    
    for name, config in registry.items():
        strategy_instance = config.strategy_class()
        
        # Serialize parameters (convert numpy arrays to lists)
        default_params = {
            k: _serialize_param_value(v) 
            for k, v in config.default_params.items()
        }
        grid_params = {
            k: _serialize_param_value(v) 
            for k, v in config.grid_params.items()
        }
        
        strategies.append(StrategyInfo(
            name=name,
            display_name=_get_display_name(name),
            market_type=strategy_instance.default_market_type.value,
            default_leverage=strategy_instance.default_leverage,
            default_params=default_params,
            grid_params=grid_params,
        ))
    
    return StrategiesResponse(strategies=strategies)
