"""
Hybrid backend: Redis for hot data, PostgreSQL for cold data.
Best of both worlds - speed + persistence + analytics.
"""

from typing import Optional, List
from datetime import datetime, timedelta

from .base import StateBackend
from .redis_backend import RedisBackend
from .postgresql_backend import PostgreSQLBackend
from ..schemas import UnifiedState


class HybridBackend(StateBackend):
    """
    Hybrid backend combining Redis (hot data) and PostgreSQL (cold data).
    
    Strategy:
    - Active sessions (< 1 hour old): Redis (fast access)
    - Inactive sessions (> 1 hour old): PostgreSQL (persistence)
    - Writes go to both (write-through cache)
    - Reads from Redis first, fallback to PostgreSQL
    
    Best for production systems needing both speed and analytics.
    """
    
    def __init__(
        self,
        redis_backend: RedisBackend,
        postgresql_backend: PostgreSQLBackend,
        hot_data_ttl_hours: int = 1,
    ):
        """
        Initialize hybrid backend.
        
        Args:
            redis_backend: Redis backend for hot data
            postgresql_backend: PostgreSQL backend for cold data
            hot_data_ttl_hours: Hours before data is considered "cold"
        """
        self.redis = redis_backend
        self.postgresql = postgresql_backend
        self.hot_data_ttl = timedelta(hours=hot_data_ttl_hours)
    
    def write_state(self, state: UnifiedState) -> bool:
        """
        Write to both Redis (hot) and PostgreSQL (persistent).
        Write-through cache pattern.
        """
        # Write to PostgreSQL (persistent)
        pg_success = self.postgresql.write_state(state)
        
        # Write to Redis (hot cache)
        redis_success = self.redis.write_state(state)
        
        return pg_success and redis_success
    
    def read_state(self, session_id: str, agent_id: str) -> Optional[UnifiedState]:
        """
        Read from Redis first (fast), fallback to PostgreSQL.
        If found in PostgreSQL, promote back to Redis.
        """
        # Try Redis first (hot data)
        state = self.redis.read_state(session_id, agent_id)
        if state is not None:
            return state
        
        # Fallback to PostgreSQL (cold data)
        state = self.postgresql.read_state(session_id, agent_id)
        if state is not None:
            # Promote back to Redis (make it hot again)
            self.redis.write_state(state)
            return state
        
        return None
    
    def delete_state(self, session_id: str, agent_id: str) -> bool:
        """Delete from both backends."""
        pg_success = self.postgresql.delete_state(session_id, agent_id)
        redis_success = self.redis.delete_state(session_id, agent_id)
        return pg_success and redis_success
    
    def list_agents(self, session_id: str) -> List[str]:
        """List agents from Redis (faster), fallback to PostgreSQL."""
        agents = self.redis.list_agents(session_id)
        if agents:
            return agents
        return self.postgresql.list_agents(session_id)
    
    def read_shared_state(self, session_id: str) -> Optional[UnifiedState]:
        """Read shared state with Redis fallback."""
        state = self.redis.read_shared_state(session_id)
        if state is not None:
            return state
        return self.postgresql.read_shared_state(session_id)
    
    def write_shared_state(self, session_id: str, state: UnifiedState) -> bool:
        """Write shared state to both backends."""
        pg_success = self.postgresql.write_shared_state(session_id, state)
        redis_success = self.redis.write_shared_state(session_id, state)
        return pg_success and redis_success
    
    def archive_cold_sessions(self, older_than_hours: int = 24):
        """
        Archive old sessions from Redis to PostgreSQL only.
        Useful for memory management.
        """
        # This would require tracking session ages
        # For now, just a placeholder for the concept
        pass
    
    def get_analytics(self, query: str, params: tuple = ()):
        """
        Run analytics queries on PostgreSQL.
        Hybrid backend advantage: fast reads + analytics.
        """
        return self.postgresql.query_states(query, params)

