from typing import Any, cast, override

from redis.client import Redis

from phederation.cache.base import BaseCache


class RedisCache(BaseCache):
    def __init__(self, max_size: int = 100, ttl: int = 300, redis_host: str = "127.0.0.1", redis_port: int = 6379, password: None | str = None):
        self.max_size: int = max_size
        self.ttl: int = ttl
        self.r: Redis = Redis(host=redis_host, port=redis_port, password=password)

    @override
    def get(self, key: str) -> None | Any:
        return self.r.get(str(key))

    @override
    def set(self, key: str, value: Any | None):
        if value:
            _ = self.r.set(name=str(key), value=value)  # pyright: ignore[reportAny]

    @override
    def delete(self, key: str):
        _ = self.r.delete(str(key))

    @override
    def clear(self, prefix: str | None = None):
        if prefix is None:
            _ = self.r.flushall(asynchronous=False)  # pyright: ignore[reportUnknownMemberType]
        else:
            keys = cast(list[str], self.r.keys(f"{prefix}*"))  # pyright: ignore[reportUnknownMemberType]
            for key in keys:
                if key.startswith(prefix):
                    _ = self.r.delete(key)


    @override
    def close(self):
        self.r.close()
