"""Configuration models for API security and performance."""

from typing import Optional, List, Dict, Any
from pathlib import Path
from pydantic import BaseModel, Field


class AzureADAuthConfig(BaseModel):
    """Azure AD authentication configuration."""
    tenant_id: str = Field(..., description="Azure AD tenant ID")
    client_id: str = Field(..., description="Application (client) ID")
    audience: str = Field(
        "api://azure-discovery",
        description="Expected audience claim in JWT tokens",
    )
    required_scopes: List[str] = Field(
        default_factory=lambda: ["Discovery.Read"],
        description="Required OAuth scopes",
    )


class APIKeyAuthConfig(BaseModel):
    """API key authentication configuration."""
    keys_file: Optional[Path] = Field(
        None,
        description="Path to JSON file containing API key hashes and metadata",
    )
    keys: Dict[str, Dict[str, Any]] = Field(
        default_factory=dict,
        description="In-memory key store (for development only)",
    )


class AuthConfig(BaseModel):
    """Authentication configuration."""
    backend: str = Field(
        "none",
        description="Authentication backend: azure_ad, api_key, or none",
    )
    azure_ad: Optional[AzureADAuthConfig] = None
    api_key: Optional[APIKeyAuthConfig] = None


class RateLimitConfig(BaseModel):
    """Rate limiting configuration."""
    enabled: bool = Field(True, description="Enable rate limiting")
    requests_per_minute: int = Field(
        60,
        description="Maximum requests per minute per client",
    )
    burst_size: int = Field(
        10,
        description="Maximum burst capacity (token bucket size)",
    )
    redis_url: Optional[str] = Field(
        None,
        description="Redis URL for distributed rate limiting (optional)",
    )


class QuotaConfig(BaseModel):
    """Usage quota configuration."""
    enabled: bool = Field(False, description="Enable quota enforcement")
    default_limit: int = Field(
        1000,
        description="Default quota limit per period",
    )
    period_days: int = Field(
        30,
        description="Quota reset period in days",
    )


class AuditLogConfig(BaseModel):
    """Audit logging configuration."""
    enabled: bool = Field(True, description="Enable audit logging")
    log_file: Optional[Path] = Field(
        None,
        description="Path to audit log file (JSONL format)",
    )
    include_request_body: bool = Field(
        False,
        description="Include request bodies in audit logs",
    )
    include_response_body: bool = Field(
        False,
        description="Include response bodies in audit logs",
    )


class ScaleControlConfig(BaseModel):
    """Scale control configuration for large tenants."""
    enabled: bool = Field(True, description="Enable adaptive rate control")
    initial_rps: float = Field(
        10.0,
        description="Initial requests per second",
    )
    min_rps: float = Field(1.0, description="Minimum requests per second")
    max_rps: float = Field(50.0, description="Maximum requests per second")
    max_concurrent_batches: int = Field(
        5,
        description="Maximum concurrent batch operations",
    )
    adaptive_batching: bool = Field(
        True,
        description="Enable adaptive batch sizing",
    )
    initial_batch_size: int = Field(
        1000,
        description="Initial batch size for paginated operations",
    )


class APIConfig(BaseModel):
    """Complete API configuration."""
    auth: AuthConfig = Field(default_factory=AuthConfig)
    rate_limit: RateLimitConfig = Field(default_factory=RateLimitConfig)
    quota: QuotaConfig = Field(default_factory=QuotaConfig)
    audit_log: AuditLogConfig = Field(default_factory=AuditLogConfig)
    scale_controls: ScaleControlConfig = Field(default_factory=ScaleControlConfig)
    
    @classmethod
    def from_toml(cls, config_file: Path) -> "APIConfig":
        """Load configuration from TOML file.
        
        Args:
            config_file: Path to TOML configuration file
            
        Returns:
            APIConfig instance
        """
        import tomli
        
        with open(config_file, "rb") as f:
            data = tomli.load(f)
        
        return cls(**data.get("api", {}))
