"""
Redis store — ultra-fast key-value lookups, optional TTL expiry.

Install:  pip install "clawid[redis]"

Usage:
    store = RedisStore("redis://localhost:6379")
    store = RedisStore("redis://localhost:6379", ttl=86400)  # expire after 24h
    store = RedisStore("rediss://user:pass@host:6380")       # TLS
"""

import json
import time

from .base import ClawIDStore


class RedisStore(ClawIDStore):

    def __init__(self, url: str = "redis://localhost:6379", ttl: int | None = None):
        """
        Args:
            url: Redis connection URL
            ttl: optional time-to-live in seconds (None = no expiry)
        """
        try:
            import redis as _redis
        except ImportError:
            raise ImportError(
                "redis is required for RedisStore.\n"
                "Install it with:  pip install 'clawid[redis]'"
            )
        self._redis = _redis.from_url(url, decode_responses=True)
        self.ttl = ttl
        self._prefix = "clawid:"

    def _key(self, clawid: str) -> str:
        return f"{self._prefix}{clawid}"

    def save(self, clawid: str, metadata: dict) -> None:
        payload = json.dumps({"metadata": metadata, "ts": time.time()})
        key = self._key(clawid)
        if self.ttl:
            self._redis.setex(key, self.ttl, payload)
        else:
            self._redis.set(key, payload)

    def get(self, clawid: str) -> dict | None:
        raw = self._redis.get(self._key(clawid))
        if raw is None:
            return None
        return json.loads(raw)["metadata"]

    def delete(self, clawid: str) -> bool:
        return self._redis.delete(self._key(clawid)) > 0

    def exists(self, clawid: str) -> bool:
        return self._redis.exists(self._key(clawid)) > 0

    def close(self) -> None:
        self._redis.close()
