"""
WaveClient — the main entry point for the Wave Business API SDK.
"""

from typing import Optional

from .aggregated_merchants import AggregatedMerchantsAPI
from .balance import BalanceAPI
from .checkout import CheckoutAPI
from .payout import PayoutAPI
from .session import WaveSession

BASE_URL = "https://api.wave.com"


class WaveClient:
    """
    Top-level client for the Wave Business API.

    Provides access to all Wave API resources through a single object:
    - ``client.balance`` — Balance & Reconciliation API
    - ``client.checkout`` — Checkout API
    - ``client.payout`` — Payout API
    - ``client.aggregated_merchants`` — Aggregated Merchants API

    Args:
        api_key: Your Wave Business API key. Keep this secret.
        signing_secret: Optional. Your API signing secret for HMAC-SHA256
                        request signing. When provided, all requests will
                        include a ``Wave-Signature`` header.
        base_url: Override the default API base URL. Useful for testing.
        timeout: HTTP request timeout in seconds (default: 30).

    Example — minimal setup::

        from wave_business_api import WaveClient

        client = WaveClient(api_key="wave_sn_prod_...")

    Example — with request signing::

        client = WaveClient(
            api_key="wave_sn_prod_...",
            signing_secret="wave_sn_AKS_...",
        )

    Example — check balance::

        balance = client.balance.get()
        print(f"Balance: {balance['amount']} {balance['currency']}")

    Example — create a checkout session::

        session = client.checkout.create_session(
            amount="2500",
            currency="XOF",
            success_url="https://mysite.com/success",
            error_url="https://mysite.com/error",
            client_reference="order-99",
        )
        # Redirect user to: session["wave_launch_url"]

    Example — send a payout::

        payout = client.payout.create(
            currency="XOF",
            receive_amount="10000",
            mobile="+221555110219",
            name="Moustapha Mbaye",
            payment_reason="Freelance payment",
        )

    Example — batch payout::

        batch = client.payout.create_batch([
            {"currency": "XOF", "receive_amount": "5000", "mobile": "+221555110219"},
            {"currency": "XOF", "receive_amount": "8000", "mobile": "+221555110233"},
        ])
        batch_result = client.payout.get_batch(batch["id"])

    Example — list transactions::

        for tx in client.balance.get_all_transactions(date="2024-01-15"):
            print(tx["transaction_id"], tx["amount"])

    Example — aggregated merchant::

        merchant = client.aggregated_merchants.create(
            name="My Sub-Merchant",
            business_type="other",
            business_description="Local retail shop",
        )
    """

    def __init__(
        self,
        api_key: str,
        signing_secret: Optional[str] = None,
        base_url: str = BASE_URL,
        timeout: int = 30,
    ):
        self._session = WaveSession(
            api_key=api_key,
            signing_secret=signing_secret,
            base_url=base_url,
            timeout=timeout,
        )
        self.balance = BalanceAPI(self._session)
        self.checkout = CheckoutAPI(self._session)
        self.payout = PayoutAPI(self._session)
        self.aggregated_merchants = AggregatedMerchantsAPI(self._session)

    def __repr__(self):
        # Mask all but last 4 characters of the API key
        masked = "..." + self._session.api_key[-4:] if len(self._session.api_key) > 4 else "****"
        return f"WaveClient(api_key='{masked}')"
