"""Backtesting API module."""

from typing import List


class BacktestAPI:
    """Access the adaptive backtesting system (advanced tier).

    Available via ``client.backtest``.
    """

    def __init__(self, client):
        self._request = client._request

    def run(self, factors: List[dict], start_date: str, end_date: str,
            top_n: int = None, rebalance_days: int = None,
            timeout: int = 300) -> dict:
        """Run an adaptive portfolio backtest.

        Args:
            factors: List of factor dicts with weights,
                e.g. ``[{"name": "ep", "weight": 0.5}, ...]``.
            start_date: Backtest start date.
            end_date: Backtest end date.
            top_n: Position count (default 30).
            rebalance_days: Rebalance period in days.
            timeout: Request timeout (default 300s).
        """
        body = {
            "factors": factors,
            "start_date": start_date,
            "end_date": end_date,
        }
        if top_n is not None:
            body["top_n"] = top_n
        if rebalance_days is not None:
            body["rebalance_days"] = rebalance_days
        return self._request(
            "POST", "/api/adaptive/backtest/run",
            data=body, timeout=timeout,
        )

    def result(self, run_id: str) -> dict:
        """Get a previously saved backtest result.

        Args:
            run_id: Backtest run ID (e.g. ``bt_20260312_xxxx``).
        """
        return self._request("GET", f"/api/adaptive/backtest/result/{run_id}")
