File size: 2,019 Bytes
b7bf9e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57e3ad5
 
 
b7bf9e4
 
57e3ad5
b7bf9e4
 
 
 
 
 
 
57e3ad5
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
Application configuration using pydantic-settings.

Reads configuration from environment variables with validation.
"""

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """
    Application settings loaded from environment variables.

    Attributes:
        database_url: PostgreSQL connection string (required)
        jwks_url: Better Auth JWKS endpoint URL for JWT verification (required)
        cors_origins: Comma-separated list of allowed CORS origins
    """

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

    database_url: str
    jwks_url: str = "http://localhost:3000/api/auth/jwks"
    cors_origins: str = "http://localhost:3000"
    openai_api_key: str = ""

    def __init__(self, **kwargs):
        import os

        super().__init__(**kwargs)
        if not self.database_url:
            raise ValueError(
                "DATABASE_URL environment variable is required. "
                "Set it in .env file or export it directly. "
                "Example: postgresql+asyncpg://user:pass@host/db?sslmode=verify-full"
            )

        # Export OPENAI_API_KEY to os.environ so the OpenAI Agents SDK can find it
        if self.openai_api_key and not os.environ.get("OPENAI_API_KEY"):
            os.environ["OPENAI_API_KEY"] = self.openai_api_key

    @property
    def cors_origin_list(self) -> list[str]:
        """Parse comma-separated CORS origins into a list."""
        return [origin.strip() for origin in self.cors_origins.split(",") if origin.strip()]


_settings: Settings | None = None


def get_settings() -> Settings:
    """
    Get cached application settings.

    Returns:
        Settings instance with validated configuration.

    Raises:
        ValueError: If required configuration is missing.
    """
    global _settings
    if _settings is None:
        _settings = Settings()
    return _settings