"""Application configuration loaded from environment variables."""

import os
from dataclasses import dataclass
from functools import lru_cache


@dataclass(frozen=True)
class Config:
    db_user: str
    db_password: str
    db_host: str
    db_port: int
    db_name: str

    celery_broker_url: str
    celery_result_backend: str

    secret_key: str
    extension_api_key: str  # used by the Firefox extension; lands in FC-3 but read here
    log_level: str

    @property
    def database_url(self) -> str:
        return (
            f"postgresql+asyncpg://{self.db_user}:{self.db_password}"
            f"@{self.db_host}:{self.db_port}/{self.db_name}"
        )

    @property
    def database_url_sync(self) -> str:
        # Alembic uses sync driver
        return (
            f"postgresql+psycopg://{self.db_user}:{self.db_password}"
            f"@{self.db_host}:{self.db_port}/{self.db_name}"
        )


@lru_cache(maxsize=1)
def get_config() -> Config:
    return Config(
        db_user=os.environ.get("DB_USER", "fabledcurator"),
        db_password=os.environ["DB_PASSWORD"],
        db_host=os.environ.get("DB_HOST", "postgres"),
        db_port=int(os.environ.get("DB_PORT", "5432")),
        db_name=os.environ.get("DB_NAME", "fabledcurator"),
        celery_broker_url=os.environ.get("CELERY_BROKER_URL", "redis://redis:6379/0"),
        celery_result_backend=os.environ.get("CELERY_RESULT_BACKEND", "redis://redis:6379/0"),
        secret_key=os.environ["SECRET_KEY"],
        extension_api_key=os.environ.get("EXTENSION_API_KEY", ""),
        log_level=os.environ.get("LOG_LEVEL", "INFO"),
    )
