"""
 — SDK Configuration
==========================================
Centralises all tuneable parameters. Instantiated once per Client.
"""

from __future__ import annotations

from dataclasses import dataclass, field

_DEFAULT_BASE_URL  = "https://nees-gp.onrender.com"
_DEFAULT_TIMEOUT   = 30          # seconds
_DEFAULT_MAX_RETRIES = 2         # attempts after the first failure
_DEFAULT_RETRY_DELAY = 1.0       # seconds between retries (exponential: ×2 each retry)
_SDK_VERSION = "0.1.0"


@dataclass
class SDKConfig:
    """
    Immutable configuration for a Client instance.

    Parameters
    ──────────
    api_key         Your NEES GP API key (Bearer token).
    base_url        Base URL of the NEES GP server.
                    Default: https://nees-gp.onrender.com
    timeout         HTTP request timeout in seconds. Default: 30.
    max_retries     How many times to retry on transient errors
                    (network error, 5xx). Default: 2.
    retry_delay_s   Initial delay between retries (doubles each attempt).
                    Default: 1.0s
    authority_state Override authority state for proposals: A | B | C.
                    Default: None (use server default).
    verify_ssl      Whether to verify SSL certificates. Default: True.
                    Set False only for local development.
    """
    api_key:         str
    base_url:        str   = _DEFAULT_BASE_URL
    timeout:         float = _DEFAULT_TIMEOUT
    max_retries:     int   = _DEFAULT_MAX_RETRIES
    retry_delay_s:   float = _DEFAULT_RETRY_DELAY
    authority_state: str   = "B"
    verify_ssl:      bool  = True

    def __post_init__(self) -> None:
        # Strip trailing slash from base_url so url joining is always clean
        self.base_url = self.base_url.rstrip("/")
        if not self.api_key:
            raise ValueError(
                "api_key is required. "
                "Pass it to Client(api_key='your-key') or set "
                "NEES_API_KEY in your environment."
            )
        if self.timeout <= 0:
            raise ValueError(f"timeout must be > 0, got {self.timeout}")
        if self.max_retries < 0:
            raise ValueError(f"max_retries must be >= 0, got {self.max_retries}")
        if self.authority_state not in ("A", "B", "C"):
            raise ValueError(
                f"authority_state must be A, B, or C — got {self.authority_state!r}"
            )

    def url(self, path: str) -> str:
        """Build a full URL from a relative path."""
        return f"{self.base_url}/{path.lstrip('/')}"

    @property
    def default_headers(self) -> dict[str, str]:
        return {
            "Authorization":  f"Bearer {self.api_key}",
            "Content-Type":   "application/json",
            "Accept":         "application/json",
            "User-Agent":     f"nees-gp-sdk/{_SDK_VERSION} python",
            "X-SDK-Version":  _SDK_VERSION,
        }
