<?php
/**
 * MCSManager API 代理脚本
 * 用于处理前端页面与 MCSManager API 的通信
 */

// 配置信息 - 请根据实际情况修改
$config = [
    'api_base_url' => 'http://154.222.30.227:23333/api', // MCSManager API 基础 URL
    'api_key' => '5ffc6f20166340fb9de0a12a02252b98',                             // MCSManager API Key
    'timeout' => 10,                                               // 请求超时时间（秒）
];

// 确保脚本不会因为执行时间过长而中断
set_time_limit(30);

// 初始化 CURL
function initCurl($url, $method = 'GET', $data = null)
{
    global $config;

    $ch = curl_init();

    // 设置 URL 和方法
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
    } else {
        if ($data) {
            $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($data);
        }
        curl_setopt($ch, CURLOPT_URL, $url);
    }

    // 设置其他选项
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $config['timeout']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 设置请求头 - 使用 API Key 替代认证令牌
    $headers = [
        'Content-Type: application/x-www-form-urlencoded',
        'Authorization: Bearer ' . $config['api_key'],
    ];

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    return $ch;
}

// 处理 API 请求
function handleApiRequest()
{
    global $config;

    // 确保有 action 参数
    if (!isset($_GET['action'])) {
        die(json_encode([
            'code' => 400,
            'message' => '缺少 action 参数'
        ]));
    }

    $action = $_GET['action'];
    $instanceUuid = isset($_GET['instanceUuid']) ? $_GET['instanceUuid'] : '';
    $daemonId = isset($_GET['daemonId']) ? $_GET['daemonId'] : '';
    $command = isset($_POST['command']) ? $_POST['command'] : '';
    $operations = isset($_GET['operations']) ? $_GET['operations'] : '';

    // 根据 action 构建 API URL
    switch ($action) {
        case 'instances':
            // 获取实例列表
            $apiUrl = $config['api_base_url'] . '/service/remote_service_instances';
            $method = 'GET';
            $data = [
                'daemonId' => $daemonId,
                'page' => isset($_GET['page']) ? $_GET['page'] : 1,
                'page_size' => isset($_GET['page_size']) ? $_GET['page_size'] : 10,
                'instance_name' => isset($_GET['instance_name']) ? $_GET['instance_name'] : '',
                'status' => isset($_GET['status']) ? $_GET['status'] : ''
            ];
            break;

        case 'instanceDetail':
            // 获取实例详情
            $apiUrl = $config['api_base_url'] . '/service/remote_service_instances';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
            ];
            break;

        case 'createInstance':
            // 创建实例
            $apiUrl = $config['api_base_url'] . '/service/remote_service_instances';
            $method = 'POST';
            $instanceConfig = json_decode(file_get_contents('php://input'), true);
            $data = [
                'config' => $instanceConfig
            ];
            break;

        case 'updateInstanceConfig':
            // 更新实例配置
            $apiUrl = $config['api_base_url'] . '/service/remote_service_instances';
            $method = 'PUT';
            $instanceConfig = json_decode(file_get_contents('php://input'), true);
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
                'config' => $instanceConfig
            ];
            break;

        case 'deleteInstance':
            // 删除实例
            $apiUrl = $config['api_base_url'] . '/service/remote_service_instances';
            $method = 'DELETE';
            $data = [
                'uuids' => [$instanceUuid],
                'deleteFile' => isset($_GET['deleteFile']) ? $_GET['deleteFile'] : false
            ];
            break;

        case 'startInstance':
            // 启动实例
            $apiUrl = $config['api_base_url'] . '/protected_instance/open';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
            ];
            break;

        case 'stopInstance':
            // 停止实例
            $apiUrl = $config['api_base_url'] . '/protected_instance/stop';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
            ];
            break;

        case 'restartInstance':
            // 重启实例
            $apiUrl = $config['api_base_url'] . '/protected_instance/restart';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
            ];
            break;

        case 'killInstance':
            // 强制结束实例进程
            $apiUrl = $config['api_base_url'] . '/protected_instance/kill';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
            ];
            break;

        case 'batchOperations':
            // 批量操作
            $apiUrl = $config['api_base_url'] . '/instance/multi_' . $operations;
            $method = 'POST';
            $instanceUuids = json_decode($_POST['instanceUuids'], true);
            $data = [];
            foreach ($instanceUuids as $uuid) {
                $data[] = [
                    'instanceUuid' => $uuid,
                    'daemonId' => $daemonId,
                ];
            }
            break;

        case 'updateInstance':
            // 更新实例
            $apiUrl = $config['api_base_url'] . '/protected_instance/asynchronous';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
                'task_name' => 'update'
            ];
            break;

        case 'sendCommand':
            // 发送命令
            $apiUrl = $config['api_base_url'] . '/protected_instance/command';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
                'command' => $command
            ];
            break;

        case 'getOutput':
            // 获取输出
            $apiUrl = $config['api_base_url'] . '/protected_instance/outputlog';
            $method = 'GET';
            $data = [
                'uuid' => $instanceUuid,
                'daemonId' => $daemonId,
                'size' => isset($_GET['size']) ? $_GET['size'] : 1024
            ];
            break;

        case 'reinstallInstance':
            // 重新安装实例
            $apiUrl = $config['api_base_url'] . '/protected_instance/install_instance';
            $method = 'POST';
            $installParams = json_decode(file_get_contents('php://input'), true);
            $data = [
                'daemonId' => $daemonId,
                'uuid' => $instanceUuid,
            ];
            $postFields = [
                'targetUrl' => $installParams['targetUrl'],
                'title' => $installParams['title'],
                'description' => $installParams['description']
            ];
            break;

        default:
            die(json_encode([
                'code' => 400,
                'message' => '不支持的 action: ' . $action
            ]));
    }

    // 初始化并执行 CURL 请求
    $ch = initCurl($apiUrl, $method, $data);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // 处理响应
    if ($httpCode === 200) {
        // 直接返回 API 响应
        header('Content-Type: application/json');
        echo $response;
    } else {
        // 返回错误信息
        die(json_encode([
            'code' => $httpCode,
            'message' => 'API 请求失败',
            'details' => $response
        ]));
    }
}

// 执行 API 请求处理
handleApiRequest();
?>