"""
会话管理模块
负责管理Jupyter服务器的连接会话
"""

from typing import Optional


class SessionManager:
    """会话管理器 - 单例模式"""
    
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if self._initialized:
            return
        
        self._url: Optional[str] = None
        self._token: Optional[str] = None
        self._initialized = True
    
    def connect(self, url: str, token: Optional[str] = None):
        """
        建立连接会话
        
        Args:
            url: Jupyter服务器地址
            token: 访问令牌
        """
        self._url = url
        self._token = token
    
    def disconnect(self):
        """断开连接会话"""
        self._url = None
        self._token = None
    
    def is_connected(self) -> bool:
        """检查是否已连接"""
        return self._url is not None
    
    def get_url(self) -> Optional[str]:
        """获取当前URL"""
        return self._url
    
    def get_token(self) -> Optional[str]:
        """获取当前token"""
        return self._token
    
    def get_session(self) -> tuple:
        """
        获取会话信息
        
        Returns:
            (url, token) 元组
            
        Raises:
            Exception: 如果未连接
        """
        if not self.is_connected():
            raise Exception("未连接到Jupyter服务器，请先调用connect")
        return self._url, self._token
    
    def get_status(self) -> dict:
        """
        获取会话状态
        
        Returns:
            会话状态字典
        """
        return {
            "connected": self.is_connected(),
            "url": self._url,
            "has_token": self._token is not None
        }


# 全局会话管理器实例
session = SessionManager()
