"""
Production configuration management
"""
import os
from typing import List, Optional
from pydantic_settings import BaseSettings
from pydantic import validator
import secrets

class Settings(BaseSettings):
    # API Configuration
    API_V1_STR: str = "/api/v1"
    PROJECT_NAME: str = "Insurance Border API"
    VERSION: str = "1.0.0"
    DESCRIPTION: str = "Production-ready Insurance Management API"
    
    # Security
    SECRET_KEY: str = secrets.token_urlsafe(32)
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    ENCRYPTION_KEY: Optional[str] = None
    
    # Database
    DATABASE_URL: str = "sqlite:///./insurance.db"
    TEST_DATABASE_URL: str = "sqlite:///./test.db"
    
    # CORS
    BACKEND_CORS_ORIGINS: List[str] = ["http://localhost:3000"]
    
    @validator("BACKEND_CORS_ORIGINS", pre=True)
    def assemble_cors_origins(cls, v):
        if isinstance(v, str) and not v.startswith("["):
            return [i.strip() for i in v.split(",")]
        elif isinstance(v, (list, str)):
            return v
        raise ValueError(v)
    
    # Rate Limiting
    RATE_LIMIT_PER_MINUTE: int = 100
    RATE_LIMIT_PER_HOUR: int = 1000
    
    # Logging
    LOG_LEVEL: str = "INFO"
    LOG_FORMAT: str = "json"
    
    # File Upload
    MAX_FILE_SIZE: int = 10485760  # 10MB
    ALLOWED_FILE_TYPES: List[str] = ["pdf", "jpg", "jpeg", "png", "doc", "docx"]
    
    # Cache
    REDIS_URL: Optional[str] = None
    CACHE_TTL: int = 3600
    
    # Production Flags
    DEBUG: bool = False
    TESTING: bool = False
    PRODUCTION: bool = True
    
    # Monitoring
    HEALTH_CHECK_INTERVAL: int = 30
    METRICS_ENABLED: bool = True
    
    # Email (for notifications)
    SMTP_HOST: Optional[str] = None
    SMTP_PORT: int = 587
    SMTP_USER: Optional[str] = None
    SMTP_USERNAME: Optional[str] = None
    SMTP_PASSWORD: Optional[str] = None
    SMTP_FROM_EMAIL: str = "noreply@insuranceborder.com"
    SMTP_FROM_NAME: str = "Insurance Border"

    # Frontend URL
    FRONTEND_URL: str = "http://localhost:5173"

    # Pepipost Configurations
    PEPIPOST_API_KEY: Optional[str] = None
    PEPIPOST_API_URL: str = "https://api.pepipost.com/v5.1/mail/send"
    PEPIPOST_FROM_EMAIL: Optional[str] = None
    PEPIPOST_FROM_NAME: Optional[str] = None

    @validator("SMTP_USERNAME", pre=True, always=True)
    def fallback_smtp_username(cls, v, values):
        # Allow SMTP_USER as fallback if SMTP_USERNAME is not set
        if v is None:
            return values.get("SMTP_USER")
        return v
    
    class Config:
        env_file = ".env"
        case_sensitive = True
        extra = "ignore"

# Global settings instance
settings = Settings()