"""Public client surface for ``gate``."""

from __future__ import annotations

import platform
import sys
from typing import Optional

import requests

from ._http import HttpClient
from .resources import EmbedResource, SessionsResource
from .webhooks import WebhooksResource

_SDK_VERSION = "0.1.0"
# API origin only — resource paths carry the `/v1` segment (see resources.py),
# matching the Node/Web SDK convention. Override via GateClient(base_url=...).
_DEFAULT_BASE_URL = "https://0gate-api.0bit.app"
_DEFAULT_TIMEOUT_SECONDS = 30.0
_DEFAULT_MAX_RETRIES = 2


class GateClient:
    """Entry point for the 0Gate ramp API.

    Mirrors the Stripe-Python shape::

        from gate import GateClient

        client = GateClient(api_key=os.environ["GATE_KEY"])
        session = client.sessions.create({
            "amount": "100.00",
            "currency": "EUR",
            "return_url": "https://myapp.example/done",
        })
        # Forward `session["client_secret"]` to the browser; pair with widget.js.

    Construct one client per API key. No global singleton — different
    keys (test vs live, multiple partners in a multi-tenant app) get
    distinct instances.
    """

    def __init__(
        self,
        *,
        api_key: str,
        base_url: Optional[str] = None,
        timeout_seconds: float = _DEFAULT_TIMEOUT_SECONDS,
        max_retries: int = _DEFAULT_MAX_RETRIES,
        app_info: Optional[str] = None,
        session: Optional[requests.Session] = None,
    ) -> None:
        if not api_key or not isinstance(api_key, str):
            raise ValueError("GateClient: `api_key` is required and must be a string")

        http = HttpClient(
            api_key=api_key,
            base_url=base_url or _DEFAULT_BASE_URL,
            timeout_seconds=timeout_seconds,
            max_retries=max_retries,
            user_agent=_build_user_agent(app_info),
            session=session,
        )

        self.sessions = SessionsResource(http)
        self.embed = EmbedResource(http)
        self.webhooks = WebhooksResource()


def _build_user_agent(app_info: Optional[str]) -> str:
    py_version = ".".join(str(p) for p in sys.version_info[:3])
    base = f"0gate/{_SDK_VERSION} python/{py_version} {platform.system().lower()}"
    return f"{base} {app_info}" if app_info else base


__all__ = ["GateClient"]
