"""
Application Configuration Settings
"""
import os
from typing import Optional
from pydantic import Field, AnyHttpUrl
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Application settings with environment variable support"""
    # Database (PostgreSQL)
    DB_NAME: str = Field(default="fastapi_db", description="Database name")
    DB_HOST: str = Field(default="localhost", description="Database host")
    DB_PORT: int = Field(default=5432,description="Database port")
    DB_USER: str = Field(default="postgres", description="Database user")
    DB_PASSWORD: str = Field(default="password", description="Database password")
    
    # Database connection pool settings
    POOL_SIZE: int = Field(default=10, description="Database connection pool size")
    MAX_POOL_OVERFLOW: int = Field(default=20, description="Maximum pool overflow connections")
    
    # Legacy DATABASE_URL (will be constructed from above fields)
    DATABASE_URL: Optional[str] = Field(default=None, description="Complete database URL (optional)")
    
    def getDbConnectionUri(self) -> str:
        """Get the database connection URI"""
        if self.DATABASE_URL:
            return self.DATABASE_URL
        
        # Default to PostgreSQL
        return f"postgresql+psycopg://{self.DB_USER}:{self.DB_PASSWORD}@{self.DB_HOST}:{self.DB_PORT}/{self.DB_NAME}"
    
    # Application
    APP_NAME: str = Field(default="FastAPI Boilerplate", description="Application name")
    APP_TITLE: str = Field(default="FastAPI Boilerplate", description="Application title")
    APP_DESCRIPTION: str = Field(default="A production-ready FastAPI application template", description="Application description")
    APP_VERSION: str = Field(default="1.0.0", description="Application version")
    APP_HOST: str = Field(default="0.0.0.0", description="Application host")
    APP_PORT: int = Field(default=8000, description="Application port")
    APP_DEBUG: bool = Field(default=True, description="Debug mode")
    APP_ENV: str = Field(default="dev", description="Application environment (dev, prod)")
    APP_SUPPORT_EMAIL: str = Field(default="support@example.com", description="Application support email")
    APP_SUPPORT_PHONE: str = Field(default="+1-555-0123", description="Application support phone")
    APP_PRIMARY_COLOR: str = Field(default="#007bff", description="Application primary color")
    APP_SECONDARY_COLOR: str = Field(default="#ca79eb", description="Application primary color")
    APP_LOGO: str = Field(default="", description="Application primary color")
    APP_LOGO_SECONDARY: str = Field(default="", description="Application primary color")
    DEBUG: bool = Field(default=True, description="Legacy debug field")
    
    # Security & JWT
    JWT_SECRET_KEY: str = Field(default="your-secret-key-here", description="JWT Secret key")
    JWT_ALGORITHM: str = Field(default="HS256", description="JWT algorithm")
    JWT_EXPIRES: int = Field(default=30, description="JWT access token expiration in minutes")
    JWT_REFRESH_EXPIRES: int = Field(default=7, description="JWT refresh token expiration in days")
    
    @property
    def jwt_secret_key(self) -> str:
        """Get JWT secret key"""
        return self.JWT_SECRET_KEY
    
    @property
    def jwt_algorithm(self) -> str:
        """Get JWT algorithm"""
        return self.JWT_ALGORITHM
    
    @property
    def jwt_expires_minutes(self) -> int:
        """Get JWT access token expiration in minutes"""
        return self.JWT_EXPIRES
    
    @property
    def jwt_refresh_expires_days(self) -> int:
        """Get JWT refresh token expiration in days"""
        return self.JWT_REFRESH_EXPIRES
    
    # Logging
    LOG_LEVEL: str = Field(default="INFO", description="Logging level")
    SQL_ECHO: bool = Field(default=False, description="SQLAlchemy echo SQL statements")
    
    # CORS
    ALLOWED_ORIGINS: list[str] = Field(default=["*"], description="Allowed CORS origins")
    CORS_ORIGINS: str = Field(default="*", description="CORS origins as comma-separated string")
    ALLOWED_METHODS: list[str] = Field(default=["*"], description="Allowed HTTP methods")
    ALLOWED_HEADERS: list[str] = Field(default=["*"], description="Allowed headers")
    SERVER_HOST: str = Field(default="http://localhost:8000", description="Allowed headers")
    SERVER_FRONT: str = Field(default="http://localhost:3000", description="Frontend server URL")
    
    # File uploads
    UPLOADS_DIR: str = Field(default="uploads", description="Directory for file uploads")
    STATIC_FILES_PATH: str = Field(default="/uploads", description="Static files URL path")
    MAX_UPLOAD_SIZE: int = Field(default=10 * 1024 * 1024, description="Max upload size in bytes (10MB)")
    
    # AWS S3 Configuration
    AWS_S3_ACCESS_KEY: str = Field(default="", description="AWS S3 access key")
    AWS_S3_SECRET_KEY: str = Field(default="", description="AWS S3 secret key")
    AWS_S3_DEFAULT_BUCKET: str = Field(default="default-bucket", description="Default AWS S3 bucket name")
    AWS_S3_REGION: str = Field(default="us-east-1", description="AWS S3 region")
    
    def api_base_url(self) -> str:
        server_host = str(self.SERVER_HOST).rstrip('/')
        api_prefix = self.API_ROUTE_PREFIX.lstrip('/')
        return f"{server_host}/{api_prefix}"
    # Route prefixes
    API_ROUTE_PREFIX: str = Field(default="/api/v1", description="API routes prefix")
    WEBHOOK_ROUTE_PREFIX: str = Field(default="/webhooks", description="Webhook routes prefix")
    PLUGIN_ROUTE_PREFIX: str = Field(default="/plugins", description="Plugin routes prefix")
    
    # Celery Configuration (Essential only)
    CELERY_BROKER_URL: str = Field(
        default="amqp://guest:guest@rabbitmq:5672//",
        description="Celery broker URL (RabbitMQ)"
    )
    CELERY_RESULT_BACKEND: str = Field(
        default="redis://redis:6379/0",
        description="Celery result backend URL (Redis)"
    )
    CELERY_TASK_DEFAULT_QUEUE: str = Field(
        default="default",
        description="Default queue name for tasks"
    )
    CELERY_TASK_ALWAYS_EAGER: bool = Field(
        default=False,
        description="Execute tasks locally instead of sending to queue (for testing)"
    )
    CELERY_LOG_LEVEL: str = Field(
        default="INFO",
        description="Celery logging level"
    )
    
    model_config = SettingsConfigDict(
        env_file=".env",
        case_sensitive=True,
        extra="ignore"  # Ignore extra environment variables
    )


# Global settings instance
settings = Settings()
