from typing import Dict, List
from datetime import datetime, timedelta
from uuid import uuid4

class SessionManager:
    def __init__(self, session_expiry_minutes: int = 30,  llm_client=None):
        """
        Initialize the session manager with a specified expiry time.
        
        Args:
            session_expiry_minutes (int): Number of minutes after which an inactive session expires
            
            llm_client: The language model client (hotelgraph in this case)
        """
        self._sessions: Dict[str, dict] = {}
        self._session_expiry_minutes = session_expiry_minutes
        self._llm_client = llm_client

    def create_session(self) -> str:
        """
        Create a new session.
        
        Returns:
            str: The newly created session ID
        """
        session_id = str(uuid4())
        self._sessions[session_id] = {
            "history": [],
            "last_access": datetime.now(),
            "metadata": {
            "session_start": datetime.now().isoformat()
            },
            "has_guest_details": False,
            "guest_name": None,
            "guest_room": None
        }
        
        return session_id


    def session_exists(self, session_id: str) -> bool:
        """
        Check if a session exists.
        
        Args:
            session_id (str): The session ID to check
            
        Returns:
            bool: True if session exists, False otherwise
        """
        return session_id in self._sessions


    def close_session(self, session_id: str) -> None:
        """
        Explicitly close a session and cleanup its thread.
        
        Args:
            session_id (str): The session ID to close
        """
        if session_id not in self._sessions:
            print(f'Session {session_id} already closed or not found')
            raise KeyError(f"Session {session_id} not found")

        try:
            # Print message before closing the session
            print('Session closed: ' + session_id)
            # Remove the session from our storage
            del self._sessions[session_id]
            
        except Exception as e:
            print(f"Error closing session {session_id}: {str(e)}")  
            
    def cleanup_expired_sessions(self) -> None:
        """Remove sessions that haven't been accessed for the specified expiry time"""
        current_time = datetime.now()
        expired_sessions = [
            session_id for session_id, data in self._sessions.items()
            if current_time - data["last_access"] > timedelta(minutes=self._session_expiry_minutes)
        ]
        
        # Close each expired session properly
        for session_id in expired_sessions:
            print('Session expired and closed: ' + session_id)
            del self._sessions[session_id]    
                                                  