"""
代码执行模块
提供代码执行功能
"""

import time
from typing import Any, Dict, Optional
from .base import client
from .session import session


def _get_default_kernel() -> str:
    """获取服务器默认内核"""
    try:
        kernelspecs = client.request('/api/kernelspecs')
        return kernelspecs.get('default', 'python3')
    except:
        return 'python3'


class CodeExecutor:
    """代码执行器"""
    
    @staticmethod
    def execute(notebook_path: str, code: str) -> Dict[str, Any]:
        """
        在指定笔记本中执行代码
        
        Args:
            notebook_path: 笔记本路径
            code: 要执行的代码
            
        Returns:
            执行结果信息
        """
        # 获取或创建会话
        sessions = client.request('/api/sessions')
        
        # 查找对应笔记本的会话
        kernel_id = None
        
        for sess in sessions:
            if sess.get('path') == notebook_path:
                kernel_id = sess.get('kernel', {}).get('id')
                break
        
        # 如果没有找到会话，创建一个新的
        if not kernel_id:
            # 获取默认内核
            default_kernel = _get_default_kernel()
            
            session_data = {
                "path": notebook_path,
                "type": "notebook",
                "kernel": {
                    "name": default_kernel
                }
            }
            new_session = client.request('/api/sessions', 'POST', session_data)
            kernel_id = new_session.get('kernel', {}).get('id')
        
        if not kernel_id:
            raise Exception("无法获取或创建内核")
        
        # 构建WebSocket端点
        url = session.get_url()
        ws_url = url.replace('http://', 'ws://').replace('https://', 'wss://').rstrip('/')
        ws_endpoint = f"{ws_url}/api/kernels/{kernel_id}/channels"
        
        return {
            "kernel_id": kernel_id,
            "code": code,
            "execution_status": "submitted",
            "message": "代码已提交执行，请查看 Jupyter Lab 界面获取结果",
            "notebook_path": notebook_path,
            "ws_endpoint": ws_endpoint
        }
    
    @staticmethod
    def execute_and_wait(notebook_path: str, code: str, timeout: int = 30) -> Dict[str, Any]:
        """
        执行代码并等待结果（未来实现）
        
        Args:
            notebook_path: 笔记本路径
            code: 要执行的代码
            timeout: 超时时间（秒）
            
        Returns:
            执行结果
        """
        # TODO: 实现WebSocket连接和结果获取
        raise NotImplementedError("此功能尚未实现，请使用execute方法")


# 导出单例
code_executor = CodeExecutor()
