"""Client for the Purple Flea Trading API (/v1/)."""

from __future__ import annotations

from typing import Any

from .client import PurpleFleaClient


class TradingClient:
    """High-level wrapper around the Purple Flea Trading service.

    All routes are prefixed with ``/v1/``.
    """

    PREFIX = "/v1"
    DEFAULT_BASE_URL = "http://80.78.27.26:3003"

    def __init__(
        self,
        api_key: str,
        base_url: str | None = None,
        timeout: float = 30.0,
    ) -> None:
        self._http = PurpleFleaClient(
            api_key,
            base_url=base_url or self.DEFAULT_BASE_URL,
            timeout=timeout,
        )

    def _path(self, route: str) -> str:
        return f"{self.PREFIX}/{route.lstrip('/')}"

    # -- auth / account ------------------------------------------------------

    def register(self, username: str, email: str, **extra: Any) -> dict[str, Any]:
        """Register a new trading account."""
        return self._http.post(self._path("register"), username=username, email=email, **extra)

    def get_account(self) -> dict[str, Any]:
        """Retrieve the authenticated trader's account details."""
        return self._http.get(self._path("account"))

    # -- markets -------------------------------------------------------------

    def list_markets(self, **filters: Any) -> dict[str, Any]:
        """List available trading markets."""
        return self._http.get(self._path("markets"), **filters)

    def get_market(self, market_id: str) -> dict[str, Any]:
        """Get details for a specific market."""
        return self._http.get(self._path(f"markets/{market_id}"))

    def get_orderbook(self, market_id: str, **params: Any) -> dict[str, Any]:
        """Get the order book for a market."""
        return self._http.get(self._path(f"markets/{market_id}/orderbook"), **params)

    # -- positions -----------------------------------------------------------

    def open_position(
        self,
        market_id: str,
        side: str,
        size: float,
        **extra: Any,
    ) -> dict[str, Any]:
        """Open a new trading position.

        Parameters
        ----------
        market_id:
            The market to trade on.
        side:
            ``"long"`` or ``"short"``.
        size:
            Position size in base currency units.
        """
        return self._http.post(
            self._path("positions"),
            market_id=market_id,
            side=side,
            size=size,
            **extra,
        )

    def close_position(self, position_id: str, **extra: Any) -> dict[str, Any]:
        """Close an existing position."""
        return self._http.post(self._path(f"positions/{position_id}/close"), **extra)

    def get_position(self, position_id: str) -> dict[str, Any]:
        """Get details of a specific position."""
        return self._http.get(self._path(f"positions/{position_id}"))

    def list_positions(self, **filters: Any) -> dict[str, Any]:
        """List all open positions."""
        return self._http.get(self._path("positions"), **filters)

    # -- referrals -----------------------------------------------------------

    def create_referral(self) -> dict[str, Any]:
        """Generate a new referral code."""
        return self._http.post(self._path("referrals"))

    def list_referrals(self) -> dict[str, Any]:
        """List all referrals and their status."""
        return self._http.get(self._path("referrals"))

    def redeem_referral(self, code: str) -> dict[str, Any]:
        """Redeem a referral code."""
        return self._http.post(self._path("referrals/redeem"), code=code)

    # -- lifecycle -----------------------------------------------------------

    def close(self) -> None:
        self._http.close()

    def __enter__(self) -> TradingClient:
        return self

    def __exit__(self, *args: object) -> None:
        self.close()
