"""Leaderboard endpoints — ``/leaderboard/*``."""

from __future__ import annotations

from typing import Any, Optional

from fireplace_gg._transport import Transport


class Leaderboard:
    """Trader leaderboard with filtering, sorting, and search."""

    def __init__(self, transport: Transport) -> None:
        self._t = transport

    def get(
        self, *, categories: Optional[str] = None, timeframe: Optional[str] = None,
        sort_by: Optional[str] = None, sort_order: Optional[str] = None,
        limit: Optional[int] = None, offset: Optional[int] = None,
        traded_in: Optional[str] = None,
        min_volume: Optional[float] = None, max_volume: Optional[float] = None,
        min_trades: Optional[int] = None, max_trades: Optional[int] = None,
        min_win_rate: Optional[float] = None, max_win_rate: Optional[float] = None,
        min_roi: Optional[float] = None, max_roi: Optional[float] = None,
        min_pnl: Optional[float] = None, max_pnl: Optional[float] = None,
        min_realized_pnl: Optional[float] = None, max_realized_pnl: Optional[float] = None,
        min_unrealized_pnl: Optional[float] = None, max_unrealized_pnl: Optional[float] = None,
        min_avg_entry_price: Optional[float] = None, max_avg_entry_price: Optional[float] = None,
        min_avg_trade_size: Optional[float] = None, max_avg_trade_size: Optional[float] = None,
        min_trades_per_day: Optional[float] = None, max_trades_per_day: Optional[float] = None,
        min_markets_traded: Optional[int] = None, max_markets_traded: Optional[int] = None,
    ) -> Any:
        """Paginated trader leaderboard with filtering and sorting.

        All parameters are optional.

        Args:
            categories: Comma-separated category filter (e.g. ``"Politics,Sports"``).
                Use ``"all"`` or omit for no filter.
            timeframe: ``"1d"``, ``"7d"``, ``"30d"``, ``"all"``
                (aliases: ``"today"``, ``"weekly"``, ``"monthly"``).
            sort_by: Field to sort by — ``"total_pnl"``, ``"volume_usd"``,
                ``"win_rate"``, ``"trade_count"``, ``"roi"``, etc.
            sort_order: ``"asc"`` or ``"desc"``.
            limit: 1-1000 (default 100).
            offset: Default 0.
            traded_in: JSON array ``[{eventId, marketIds[]}]`` to filter
                traders who traded in specific markets.
            min_volume / max_volume: Volume USD filter.
            min_trades / max_trades: Trade count filter.
            min_win_rate / max_win_rate: Win rate filter.
            min_roi / max_roi: ROI filter.
            min_pnl / max_pnl: Total PnL filter.
            min_realized_pnl / max_realized_pnl: Realized PnL filter.
            min_unrealized_pnl / max_unrealized_pnl: Unrealized PnL filter.
            min_avg_entry_price / max_avg_entry_price: Avg entry price filter.
            min_avg_trade_size / max_avg_trade_size: Avg trade size filter.
            min_trades_per_day / max_trades_per_day: Trades/day filter.
            min_markets_traded / max_markets_traded: Markets traded filter.
        """
        return self._t.get("/leaderboard/leaderboard", params={
            "categories": categories, "timeframe": timeframe,
            "sort_by": sort_by, "sort_order": sort_order,
            "limit": limit, "offset": offset, "tradedIn": traded_in,
            "min_volume": min_volume, "max_volume": max_volume,
            "min_trades": min_trades, "max_trades": max_trades,
            "min_win_rate": min_win_rate, "max_win_rate": max_win_rate,
            "min_roi": min_roi, "max_roi": max_roi,
            "min_pnl": min_pnl, "max_pnl": max_pnl,
            "min_realized_pnl": min_realized_pnl, "max_realized_pnl": max_realized_pnl,
            "min_unrealized_pnl": min_unrealized_pnl, "max_unrealized_pnl": max_unrealized_pnl,
            "min_avg_entry_price": min_avg_entry_price, "max_avg_entry_price": max_avg_entry_price,
            "min_avg_trade_size": min_avg_trade_size, "max_avg_trade_size": max_avg_trade_size,
            "min_trades_per_day": min_trades_per_day, "max_trades_per_day": max_trades_per_day,
            "min_markets_traded": min_markets_traded, "max_markets_traded": max_markets_traded,
        })

    def search(
        self, *, q: Optional[str] = None, traded_in: Optional[str] = None,
        categories: Optional[str] = None, timeframe: Optional[str] = None,
        sort_by: Optional[str] = None, sort_order: Optional[str] = None,
        limit: Optional[int] = None, offset: Optional[int] = None,
        min_volume: Optional[float] = None, max_volume: Optional[float] = None,
        min_trades: Optional[int] = None, max_trades: Optional[int] = None,
        min_win_rate: Optional[float] = None, max_win_rate: Optional[float] = None,
        min_roi: Optional[float] = None, max_roi: Optional[float] = None,
        min_pnl: Optional[float] = None, max_pnl: Optional[float] = None,
    ) -> Any:
        """Search leaderboard by wallet address or username.

        Searches for traders by text query (username, wallet address, pseudonym,
        X username) and returns their leaderboard stats. Search strategy: Full
        Ethereum address = exact wallet lookup; Partial ``0x...`` prefix = prefix
        regex match; Text = MongoDB text index search with regex fallback.

        At least one of ``q`` or ``traded_in`` is required.

        Args:
            q: Search query (required if no ``traded_in``).
            traded_in: JSON array ``[{eventId, marketIds[]}]`` (required if no ``q``).
            categories: Category filter.
            timeframe: ``"1d"``, ``"7d"``, ``"30d"``, ``"all"``.
            sort_by: Sort field.
            sort_order: ``"asc"`` or ``"desc"``.
            limit: Number of results.
            offset: Pagination offset.
            min_volume / max_volume: Volume filter.
            min_trades / max_trades: Trade count filter.
            min_win_rate / max_win_rate: Win rate filter.
            min_roi / max_roi: ROI filter.
            min_pnl / max_pnl: PnL filter.
        """
        return self._t.get("/leaderboard/search", params={
            "q": q, "tradedIn": traded_in, "categories": categories,
            "timeframe": timeframe, "sort_by": sort_by, "sort_order": sort_order,
            "limit": limit, "offset": offset,
            "min_volume": min_volume, "max_volume": max_volume,
            "min_trades": min_trades, "max_trades": max_trades,
            "min_win_rate": min_win_rate, "max_win_rate": max_win_rate,
            "min_roi": min_roi, "max_roi": max_roi,
            "min_pnl": min_pnl, "max_pnl": max_pnl,
        })

    def user(self, user_address: str) -> Any:
        """Get detailed performance stats for a single trader.

        Returns stats across all categories and timeframes, including
        username, cash balance, and first/last trade timestamps.

        Args:
            user_address: Ethereum wallet address of the trader. **Required.**
        """
        return self._t.get(f"/leaderboard/leaderboard/user/{user_address}")

    def categories(self) -> Any:
        """Get available leaderboard categories.

        Returns the list of all categories available for leaderboard filtering.
        """
        return self._t.get("/leaderboard/leaderboard/categories")
