"""
内核管理模块
提供内核的列表、重启等操作
"""

from typing import Any, Dict, List, Optional
from .base import client


class KernelManager:
    """内核管理器"""
    
    @staticmethod
    def list_all() -> Dict[str, Any]:
        """
        列出所有运行中的内核和可用的内核规格
        
        Returns:
            包含运行中内核和可用内核规格的字典
        """
        # 获取运行中的内核
        running_kernels = client.request('/api/kernels')
        
        # 获取可用的内核规格
        kernelspecs = client.request('/api/kernelspecs')
        
        return {
            "running_kernels": running_kernels,
            "running_count": len(running_kernels),
            "available_specs": kernelspecs.get('kernelspecs', {}),
            "default_kernel": kernelspecs.get('default', 'python3')
        }
    
    @staticmethod
    def get_info(kernel_id: str) -> Dict[str, Any]:
        """
        获取内核信息
        
        Args:
            kernel_id: 内核ID
            
        Returns:
            内核信息
        """
        return client.request(f'/api/kernels/{kernel_id}')
    
    @staticmethod
    def restart(kernel_id: Optional[str] = None) -> Dict[str, Any]:
        """
        重启内核
        
        Args:
            kernel_id: 内核ID（None表示重启所有内核）
            
        Returns:
            重启结果
        """
        if kernel_id:
            # 重启指定内核
            client.request(f'/api/kernels/{kernel_id}/restart', 'POST')
            return {"kernel_id": kernel_id, "status": "restarted"}
        else:
            # 重启所有内核
            kernel_info = KernelManager.list_all()
            running_kernels = kernel_info.get('running_kernels', [])
            results = []
            for kernel in running_kernels:
                kid = kernel.get('id')
                if kid:
                    client.request(f'/api/kernels/{kid}/restart', 'POST')
                    results.append({"kernel_id": kid, "status": "restarted"})
            return {"restarted_kernels": results, "total": len(results)}
    
    @staticmethod
    def interrupt(kernel_id: str) -> Dict[str, Any]:
        """
        中断内核
        
        Args:
            kernel_id: 内核ID
            
        Returns:
            中断结果
        """
        client.request(f'/api/kernels/{kernel_id}/interrupt', 'POST')
        return {"kernel_id": kernel_id, "status": "interrupted"}
    
    @staticmethod
    def shutdown(kernel_id: str) -> Dict[str, Any]:
        """
        关闭内核
        
        Args:
            kernel_id: 内核ID
            
        Returns:
            关闭结果
        """
        client.request(f'/api/kernels/{kernel_id}', 'DELETE')
        return {"kernel_id": kernel_id, "status": "shutdown"}


# 导出单例
kernel_manager = KernelManager()
