"""Historical Backtesting & Walk-Forward Endpoints."""
from __future__ import annotations

from typing import Any

from fastapi import APIRouter
from pydantic import BaseModel

from backend.app.backtesting.engine import backtest_engine
from backend.app.backtesting.walk_forward import walk_forward_validator
from backend.app.market_data.feed_manager import feed_manager

router = APIRouter(prefix="/backtest", tags=["Backtesting"])


class BacktestRunRequest(BaseModel):
    symbol: str = "BTCUSDT"
    interval: str = "15m"
    bars: int = 250
    initial_equity: float = 10000.0


@router.post("/run")
async def run_backtest(req: BacktestRunRequest) -> dict[str, Any]:
    """Execute historical event-driven simulation with friction and benchmarks."""
    candles = feed_manager.fetch_klines(req.symbol, req.interval, req.bars)
    report, trades, equity_curve = backtest_engine.run(candles)

    trade_ledger = [
        {
            "entry_time": t.entry_time,
            "exit_time": t.exit_time,
            "symbol": t.symbol,
            "side": t.side,
            "quantity": t.quantity,
            "entry_price": t.entry_price,
            "exit_price": t.exit_price,
            "pnl": round(t.pnl, 2),
            "fee_paid": round(t.fee_paid, 2),
            "exit_reason": t.exit_reason,
        }
        for t in trades
    ]

    return {
        "summary": report.__dict__,
        "equity_curve": [round(eq, 2) for eq in equity_curve],
        "trades": trade_ledger,
    }


@router.post("/walk-forward")
async def run_walk_forward(req: BacktestRunRequest) -> dict[str, Any]:
    """Execute rolling out-of-sample walk-forward validation with purging and embargo."""
    candles = feed_manager.fetch_klines(req.symbol, req.interval, req.bars)
    res = walk_forward_validator.run_validation(candles)
    return res
