<?php

// 加载全局的自动加载文件
require_once '/root/.composer/vendor/autoload.php';

// 加载本地的自动加载文件
require_once __DIR__ . '/vendor/autoload.php';

// 启动覆盖率
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);



use Workerman\Worker;


// 创建一个 Websocket server
$ws_worker = new Worker('websocket://0.0.0.0:2346');
$ws_worker->onConnect = 'onWebSocketConnect';
$ws_worker->onMessage = 'onWebSocketMessage';
$ws_worker->onClose = 'onWebSocketClose';
$ws_worker->onWorkerStop = 'onWorkerStopping';


function onWebSocketConnect($connection)
{
    echo "New connection\n";
}

function onWebSocketMessage($connection, $data)
{
    $request = json_decode($data, true);

    if (isset($request['action'])) {
        $action = $request['action'];
        $className = '\app\actions\\' . ($action);

        if (class_exists($className)) {
            $instance = new $className();
            $param = $request['param'] ?? [];
            $response = $instance->handle($param);
            $connection->send(json_encode($response));
        } else {
            $connection->send(json_encode(['error' => 'Class not found']));
        }
    } else {
        $connection->send(json_encode(['error' => 'Invalid request']));
    }
}

function onWebSocketClose($connection)
{
    echo "Connection closed\n";
}

function onWorkerStopping()
{
    echo "\nWorker is stopping...\n";

    // 停止并保存 Xdebug 覆盖率
    $coverage = xdebug_get_code_coverage();
    xdebug_stop_code_coverage();

    $filename = __DIR__ . '/coverage.json';
    file_put_contents($filename, json_encode($coverage, JSON_PRETTY_PRINT));
    echo "✅ 覆盖率已保存到 $filename\n";
}

Worker::runAll();