<?php

require_once __DIR__ . '/vendor/autoload.php';
use WebSocket\Client;

// 步骤 0：清理潜在残留进程
echo "🧹 正在关闭可能存在的旧 Workerman 实例...\n";
exec('php ' . __DIR__ . '/start1.phpunit.php stop');

// 步骤 1：生成测试入口
echo "🛠 正在生成 phpunit 入口文件...\n";
require_once __DIR__ . '/build_phpunit_entry.php';

// 步骤 2：启动服务（异步进程）
echo "🚀 启动 Workerman 服务...\n";
$process = proc_open(
    'php ' . __DIR__ . '/start1.phpunit.php start',
    [STDIN, STDOUT, STDERR],
    $pipes
);

if (!is_resource($process)) {
    echo "❌ 启动服务失败\n";
    exit(1);
}

sleep(2); // 等待服务启动

// 步骤 3：发送 WebSocket 测试请求
try {
    $client = new Client("ws://127.0.0.1:2346");

    $request = [
        "action" => "getPHPInfo",
        "param"  => [
            "sel" => true
        ]
    ];

    $client->send(json_encode($request));

    $response = $client->receive();

    echo "✅ 服务端响应:\n$response\n";



    $request = [
        "action" => "getPHPInfo",
        "param"  => [
            "sel" => false
        ]
    ];

    $client->send(json_encode($request));

    $response = $client->receive();

    echo "✅ 服务端响应:\n$response\n";


    $client->close();
} catch (Exception $e) {
    echo "❌ WebSocket 测试失败: " . $e->getMessage() . "\n";
    proc_terminate($process);
    proc_close($process);
    exit(1);
}

sleep(2); // 等待 onWorkerStopping() 执行完覆盖率保存

// 步骤 4：关闭服务进程
echo "🛑 关闭服务进程...\n";
proc_terminate($process);
proc_close($process);

/*
// 步骤 5：删除临时入口文件
$tempFile = __DIR__ . '/start1.phpunit.php';
if (file_exists($tempFile)) {
    unlink($tempFile);
    echo "🧹 已删除临时入口文件 start1.phpunit.php\n";
} else {
    echo "⚠️ 未找到 start1.phpunit.php，无需删除\n";
}

echo "✅ 测试完成，覆盖率保存在 coverage.json 中\n";
*/