<?php

declare(strict_types=1);

// 纯 PHP 轮询文件监控（跨平台兜底）：目录内 php/json/.env 的 mtime 变化 -> 重启 workerman。
// 生产环境无需此脚本，改代码后手动 php artisan workerman:serve restart 即可。

$root = dirname(__DIR__);
$dirs = ['app', 'plugins', 'routes', 'config'];
$extraFiles = ['.env'];
$interval = 1; // 秒

function snapshot(array $dirs, array $extraFiles, string $root): array
{
    $state = [];

    foreach ($dirs as $dir) {
        $path = $root.'/'.$dir;

        if (! is_dir($path)) {
            continue;
        }

        $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS));

        foreach ($it as $file) {
            if (in_array($file->getExtension(), ['php', 'json'], true)) {
                $state[$file->getPathname()] = $file->getMTime();
            }
        }
    }

    foreach ($extraFiles as $file) {
        $path = $root.'/'.$file;

        if (is_file($path)) {
            $state[$path] = filemtime($path);
        }
    }

    ksort($state);

    return $state;
}

function restartWorkerman(string $root): void
{
    echo '['.date('H:i:s').'] 检测到代码变更，重启 workerman:serve...'.PHP_EOL;
    passthru('cd '.escapeshellarg($root).' && php artisan workerman:serve restart');
}

echo '[watch] 开始监听（PHP 轮询 '.$interval.'s）：'.implode(' ', $dirs).' .env'.PHP_EOL;
$prev = snapshot($dirs, $extraFiles, $root);

while (true) {
    sleep($interval);
    $current = snapshot($dirs, $extraFiles, $root);

    if ($current !== $prev) {
        restartWorkerman($root);
        $prev = snapshot($dirs, $extraFiles, $root);
    }
}
