import os
from typing import Optional

from pydantic_settings import BaseSettings, SettingsConfigDict


class WorkerSettings(BaseSettings):
    worker_name: str = "xiaoxia-saas-worker"
    broker_url: str = "redis://redis:6379/0"
    result_backend: str = "redis://redis:6379/1"
    worker_concurrency: int = 4
    worker_max_tasks_per_child: int = 1000
    database_url: str = "postgresql+psycopg://postgres:postgres@postgres:5432/xiaoxia_saas"
    database_pool_size: int = 20
    database_max_overflow: int = 40
    database_pool_timeout: int = 30
    database_pool_recycle: int = 3600
    environment: str = "development"
    auto_create_schema: bool = False

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
    )


_settings: Optional[WorkerSettings] = None


def get_settings() -> WorkerSettings:
    global _settings
    if _settings is None:
        env = os.getenv("APP_ENV", "development")
        env_file = f".env.{env}" if env != "development" else ".env"
        if os.path.exists(env_file):
            _settings = WorkerSettings(_env_file=env_file)
        else:
            _settings = WorkerSettings()
    return _settings
