from typing import Optional
import redis # type: ignore
from .session import SessionState

class RedisStorage:
    def __init__(self, redis_url: str):
        self.client = redis.from_url(redis_url)

    def save_session(self, session_id: str, state: SessionState, ttl: int = 1800) -> None:
        """
        Save session state to Redis with TTL.
        """
        key = state.to_redis_key(session_id)
        data = state.serialize()
        self.client.setex(key, ttl, data)

    def load_session(self, session_id: str) -> Optional[SessionState]:
        """
        Load session state from Redis.
        """
        key = f"session:{session_id}:state"
        data = self.client.get(key)
        if not data:
            return None
            
        try:
            return SessionState.deserialize(data)
        except Exception as e:
            # Log error?
            print(f"Error deserializing session {session_id}: {e}")
            return None
