"""
Authevo SDK Configuration

Centralized configuration management with environment variable support.
"""

import os
from dataclasses import dataclass
from typing import Optional
from .exceptions import ConfigurationError


@dataclass
class AuthevoConfig:
    """
    SDK configuration with support for environment variables.
    
    Attributes:
        api_url: Base URL for Authevo API
        api_key: API key for authentication (optional for local dev)
        opa_url: URL for OPA policy engine (optional)
        timeout: Request timeout in seconds
        max_retries: Maximum number of retry attempts
        verify_ssl: Whether to verify SSL certificates (set False for local dev)
    
    Example:
        # Load from environment
        config = AuthevoConfig.from_env()
        
        # Or create manually
        config = AuthevoConfig(
            api_url="https://api.authevo.com",
            api_key="authevo_..."
        )
    """
    
    api_url: str
    api_key: Optional[str] = None
    opa_url: Optional[str] = None
    timeout: int = 30
    max_retries: int = 3
    verify_ssl: bool = True
    
    def __post_init__(self):
        """Validate configuration after initialization."""
        # Normalize URLs (remove trailing slash)
        self.api_url = self.api_url.rstrip('/')
        if self.opa_url:
            self.opa_url = self.opa_url.rstrip('/')
        
        # Validate timeout
        if self.timeout <= 0:
            raise ConfigurationError("Timeout must be positive")
        
        # Validate max_retries
        if self.max_retries < 0:
            raise ConfigurationError("Max retries must be non-negative")
        
        # Validate API URL format
        if not self.api_url.startswith(('http://', 'https://')):
            raise ConfigurationError(
                f"Invalid API URL: {self.api_url}. Must start with http:// or https://"
            )
    
    @classmethod
    def from_env(cls) -> "AuthevoConfig":
        """
        Load configuration from environment variables.
        
        Environment variables:
            AUTHEVO_API_URL: API base URL (default: https://api.authevo.com)
            AUTHEVO_API_KEY: API authentication key
            AUTHEVO_OPA_URL: OPA policy engine URL
            AUTHEVO_TIMEOUT: Request timeout in seconds (default: 30)
            AUTHEVO_MAX_RETRIES: Maximum retry attempts (default: 3)
            AUTHEVO_VERIFY_SSL: Verify SSL certificates (default: true)
        
        Returns:
            AuthevoConfig instance with values from environment
        """
        # Determine default API URL based on environment
        default_api_url = os.getenv(
            "AUTHEVO_API_URL",
            "https://api.authevo.com" if os.getenv("AUTHEVO_ENV") == "production"
            else "http://localhost:4000"
        )
        
        return cls(
            api_url=os.getenv("AUTHEVO_API_URL", default_api_url),
            api_key=os.getenv("AUTHEVO_API_KEY"),
            opa_url=os.getenv("AUTHEVO_OPA_URL"),
            timeout=int(os.getenv("AUTHEVO_TIMEOUT", "30")),
            max_retries=int(os.getenv("AUTHEVO_MAX_RETRIES", "3")),
            verify_ssl=os.getenv("AUTHEVO_VERIFY_SSL", "true").lower() != "false"
        )
    
    @property
    def is_production(self) -> bool:
        """Check if configuration is for production environment."""
        return "api.authevo.com" in self.api_url
    
    @property
    def is_local(self) -> bool:
        """Check if configuration is for local development."""
        return "localhost" in self.api_url or "127.0.0.1" in self.api_url
