from pydantic import BaseModel
from pydantic_settings import BaseSettings, SettingsConfigDict


class Credentials(BaseModel):
    username: str = ""
    password: str = ""


class DavSettings(BaseModel):
    """
    Connection to a DAV server.
    """

    protocol: str = "https"
    host: str = "example.com"
    path: str = "/remote.php/webdav"
    prefix: str = "/advent22"

    auth: Credentials = Credentials(
        username="advent22_user",
        password="password",
    )

    cache_ttl: int = 60 * 10
    config_filename: str = "config.toml"

    @property
    def url(self) -> str:
        """
        Combined DAV URL.
        """

        return f"{self.protocol}://{self.host}{self.path}{self.prefix}"


class RedisSettings(BaseModel):
    """
    Connection to a redis server.
    """

    host: str = "localhost"
    port: int = 6379
    db: int = 0
    protocol: int = 3


class Settings(BaseSettings):
    """
    Per-run settings.
    """

    model_config = SettingsConfigDict(
        env_prefix="ADVENT22__",
        env_file="api.conf",
        env_file_encoding="utf-8",
        env_nested_delimiter="__",
    )

    #####
    # general settings
    #####

    production_mode: bool = False
    ui_directory: str = "/opt/advent22/ui"

    #####
    # openapi settings
    #####

    def __dev_value[T](self, value: T) -> T | None:
        if self.production_mode:
            return None

        return value

    @property
    def openapi_url(self) -> str | None:
        return self.__dev_value("/api/openapi.json")

    @property
    def docs_url(self) -> str | None:
        return self.__dev_value("/api/docs")

    @property
    def redoc_url(self) -> str | None:
        return self.__dev_value("/api/redoc")

    #####
    # webdav settings
    #####

    webdav: DavSettings = DavSettings()
    redis: RedisSettings = RedisSettings()


SETTINGS = Settings()
