from __future__ import annotations
from typing import Optional, List
from ..core.events import BusEvent
from .store import Checkpoint

class RedisEventStore:
    def __init__(self, redis_url: str):
        self.redis_url = redis_url
        try:
            import redis  # type: ignore
        except Exception as e:  # pragma: no cover
            raise RuntimeError("redis extra not installed. pip install adi-agentic-agi[redis]") from e
        self._redis = redis.Redis.from_url(redis_url)

    async def put_event(self, event: BusEvent) -> None:
        self._redis.hset("events", event.event_id, event.model_dump_json())
        self._redis.rpush("event_order", event.event_id)

    async def get_event(self, event_id: str) -> Optional[BusEvent]:
        raw = self._redis.hget("events", event_id)
        if not raw:
            return None
        return BusEvent.model_validate_json(raw)

    async def list_recent(self, limit: int = 100) -> List[BusEvent]:
        ids = self._redis.lrange("event_order", -limit, -1)
        out: List[BusEvent] = []
        for i in ids:
            ev = await self.get_event(i.decode("utf-8"))
            if ev:
                out.append(ev)
        return out

    async def checkpoint(self, notes: str = "") -> Checkpoint:
        import time, uuid
        return Checkpoint(checkpoint_id=str(uuid.uuid4()), ts=time.time(), notes=notes)
