import requests
import json
import os
import glob
import time
import requests
import json
from typing import List, Dict, Union, Optional, Any

def execute_code_batch(
    batch_code: List[str], 
    max_length: Optional[int] = None, 
    max_workers: Optional[int] = 4
) -> Dict:
    """
    调用远程代码执行API执行批量代码

    :param batch_code: 代码片段列表，每个元素是一个完整的代码字符串
    :param max_length: 输出限制的最大长度，默认为None，表示使用API默认值
    :param max_workers: 批量执行的最大线程数，默认为4
    :return: API返回的JSON响应
    :raises: 
        - requests.exceptions.RequestException: 当请求失败时
        - json.JSONDecodeError: 当响应不是有效JSON时
    """
    # API端点
    url = "http://0.0.0.0:3999/execute"
    headers = {"Content-Type": "application/json"}
    
    # 构建请求载荷
    payload: dict[str, Any] = {"batch_code": batch_code}
    
    # 添加可选参数
    if max_length is not None:
        payload["max_length"] = max_length
    
    if max_workers is not None:
        payload["max_workers"] = max_workers
    

    if len(batch_code) <= 1:
        payload["max_workers"] = 1
    
    # 发送请求
    response = requests.post(url, headers=headers, json=payload)
    
    # 检查响应状态
    response.raise_for_status()
    
    # 解析并返回JSON响应
    result =response.json()
    return result

# 执行所有请求
if __name__ == "__main__":
    # try:
        # 示例: 执行简单代码
    result = execute_code_batch(
        batch_code=["print('Hello, World!')"],
        max_length=1000,
        max_workers=2
    )
    

    print(json.dumps(result, indent=2, ensure_ascii=False))
