"""State persistence for recovery."""

import json
from datetime import datetime
from typing import Dict, Any, Optional
from sqlalchemy.orm import Session
from src.core.database import get_database, AppState
from src.core.logger import get_logger

logger = get_logger(__name__)


class StateManager:
    """Manages application state persistence."""
    
    def __init__(self):
        """Initialize state manager."""
        self.db = get_database()
        self.logger = get_logger(__name__)
    
    def save_state(self, key: str, value: Any):
        """Save application state.
        
        Args:
            key: State key
            value: State value (must be JSON serializable)
        """
        session = self.db.get_session()
        try:
            existing = session.query(AppState).filter_by(key=key).first()
            if existing:
                existing.value = value
                existing.updated_at = datetime.utcnow()
            else:
                state = AppState(key=key, value=value, updated_at=datetime.utcnow())
                session.add(state)
            session.commit()
        except Exception as e:
            session.rollback()
            logger.error(f"Failed to save state {key}: {e}")
        finally:
            session.close()
    
    def load_state(self, key: str, default: Any = None) -> Any:
        """Load application state.
        
        Args:
            key: State key
            default: Default value if not found
            
        Returns:
            State value or default
        """
        session = self.db.get_session()
        try:
            state = session.query(AppState).filter_by(key=key).first()
            return state.value if state else default
        finally:
            session.close()
    
    def clear_state(self, key: str):
        """Clear application state.
        
        Args:
            key: State key
        """
        session = self.db.get_session()
        try:
            state = session.query(AppState).filter_by(key=key).first()
            if state:
                session.delete(state)
                session.commit()
        except Exception as e:
            session.rollback()
            logger.error(f"Failed to clear state {key}: {e}")
        finally:
            session.close()


# Global state manager
_state_manager: Optional[StateManager] = None


def get_state_manager() -> StateManager:
    """Get global state manager instance."""
    global _state_manager
    if _state_manager is None:
        _state_manager = StateManager()
    return _state_manager

