from pydantic_settings import BaseSettings, SettingsConfigDict
from redis import Redis


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file="../.env", env_file_encoding="utf-8", case_sensitive=True
    )
    AWS_ACCESS_KEY_ID: str | None = None
    AWS_SECRET_ACCESS_KEY: str | None = None
    AWS_REGION: str | None = None
    REDIS_URI: str | None = None


settings = Settings()  # type: ignore


class InMemoryRedis(Redis):
    __slots__ = ("_store",)

    def __init__(self) -> None:
        self._store: dict[str, bytes] = {}

    def get(self, key: str) -> bytes | None:
        return self._store.get(key)

    def set(self, key: str, value, ex=None) -> bool:  # noqa: ANN001
        if isinstance(value, bytes):
            payload = value
        else:
            payload = str(value).encode("utf-8")
        self._store[key] = payload
        return True


redis = (
    Redis.from_url(settings.REDIS_URI)
    if settings.REDIS_URI
    else InMemoryRedis()
)
