"""Configuration for ZenOTC SDK."""

from __future__ import annotations

import os
from enum import Enum
from typing import Optional

from pydantic import BaseModel, Field, field_validator


class Environment(str, Enum):
    """API environment."""

    PRODUCTION = "production"
    SANDBOX = "sandbox"


class Config(BaseModel):
    """SDK configuration."""

    api_key: str = Field(..., description="API key for authentication")
    api_secret: str = Field(..., description="API secret for authentication")
    environment: Environment = Field(
        default=Environment.PRODUCTION, description="API environment"
    )
    base_url: Optional[str] = Field(
        default=None, description="Override base URL (optional)"
    )
    timeout: float = Field(default=30.0, ge=1.0, le=300.0, description="Request timeout in seconds")
    max_retries: int = Field(default=3, ge=0, le=10, description="Maximum retry attempts")
    rate_limit_per_second: int = Field(
        default=10, ge=1, le=100, description="Rate limit per second"
    )
    websocket_ping_interval: float = Field(
        default=30.0, ge=5.0, le=60.0, description="WebSocket ping interval in seconds"
    )

    model_config = {"frozen": True}

    @field_validator("api_key", "api_secret")
    @classmethod
    def validate_not_empty(cls, v: str) -> str:
        """Validate that credentials are not empty."""
        if not v or not v.strip():
            raise ValueError("Value cannot be empty")
        return v.strip()

    @property
    def effective_base_url(self) -> str:
        """Get the effective base URL based on configuration."""
        if self.base_url:
            return self.base_url.rstrip("/")
        if self.environment == Environment.SANDBOX:
            return "https://api-staging.zenotc.com"
        return "https://api.zenotc.com"

    @property
    def websocket_url(self) -> str:
        """Get the WebSocket URL."""
        base = self.effective_base_url
        if base.startswith("https://"):
            return base.replace("https://", "wss://") + "/ws"
        return base.replace("http://", "ws://") + "/ws"

    @classmethod
    def from_env(cls) -> Config:
        """Create configuration from environment variables."""
        api_key = os.environ.get("ZENOTC_API_KEY")
        api_secret = os.environ.get("ZENOTC_API_SECRET")

        if not api_key or not api_secret:
            raise ValueError(
                "ZENOTC_API_KEY and ZENOTC_API_SECRET environment variables are required"
            )

        environment_str = os.environ.get("ZENOTC_ENVIRONMENT", "production")
        try:
            environment = Environment(environment_str.lower())
        except ValueError:
            environment = Environment.PRODUCTION

        base_url = os.environ.get("ZENOTC_BASE_URL")

        return cls(
            api_key=api_key,
            api_secret=api_secret,
            environment=environment,
            base_url=base_url,
        )
