"""RunBlob SDK configuration."""
from __future__ import annotations

import os
from dataclasses import dataclass, field

from ._version import __version__


@dataclass(frozen=True, slots=True)
class ClientConfig:
    """Immutable client configuration."""

    api_key: str
    base_url: str = "https://platform.runblob.io"
    timeout: float = 120.0
    max_retries: int = 3
    max_connections: int = 100
    max_keepalive_connections: int = 20
    keepalive_expiry: float = 30.0
    version: str = field(default=__version__, init=False)

    # Circuit breaker
    circuit_breaker_threshold: int = 5
    circuit_breaker_timeout: float = 60.0

    # Rate limiter (requests per second)
    rate_limit_rps: float = 50.0

    # Cache TTL seconds
    cache_ttl: float = 30.0
    cache_max_size: int = 256

    def __post_init__(self) -> None:
        if not self.api_key:
            raise ValueError(
                "API key is required. Pass api_key= or set RUNBLOB_API_KEY environment variable."
            )

    def __repr__(self) -> str:
        masked = self.api_key[:6] + "..." + self.api_key[-4:] if len(self.api_key) > 10 else "***"
        return f"ClientConfig(api_key='{masked}', base_url='{self.base_url}')"

    def __str__(self) -> str:
        return self.__repr__()


def resolve_api_key(api_key: str | None) -> str:
    """Resolve API key from argument or environment."""
    key = api_key or os.environ.get("RUNBLOB_API_KEY")
    if not key:
        raise ValueError(
            "API key is required. Pass api_key= or set RUNBLOB_API_KEY environment variable."
        )
    return key
