<?php

declare(strict_types=1);

namespace support\bootstrap;

use Workerman\Worker;

/**
 * 模块加载引导：迁移自 app\common\service\moduleService
 * 在 webman 启动时加载已启用模块的 AppInit 逻辑
 */
class ModuleInit implements \Webman\Bootstrap
{
    public static function start(?Worker $worker): void
    {
        $modulesDir = rtrim(base_path(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR;
        if (!is_dir($modulesDir)) {
            return;
        }

        $installed = self::installedList($modulesDir);
        foreach ($installed as $item) {
            if (($item['state'] ?? 0) != 1) {
                continue;
            }
            $uid = $item['uid'] ?? '';
            if (!$uid) {
                continue;
            }
            $moduleClass = self::getModuleEventClass($uid);
            if ($moduleClass && class_exists($moduleClass) && method_exists($moduleClass, 'AppInit')) {
                try {
                    $handle = new $moduleClass();
                    $handle->AppInit();
                } catch (\Throwable $e) {
                    // 模块 AppInit 异常不阻断启动，仅记录
                    if (class_exists(\support\Log::class)) {
                        \support\Log::warning('[ModuleInit] ' . $uid . ': ' . $e->getMessage());
                    }
                }
            }
        }
    }

    /**
     * 获取已安装模块列表（与 Server::installedList 逻辑一致）
     */
    protected static function installedList(string $dir): array
    {
        $installedDir = @scandir($dir);
        if ($installedDir === false) {
            return [];
        }
        $installedList = [];
        foreach ($installedDir as $item) {
            if ($item === '.' || $item === '..' || is_file($dir . $item)) {
                continue;
            }
            $tempDir = $dir . $item . DIRECTORY_SEPARATOR;
            if (!is_dir($tempDir)) {
                continue;
            }
            $info = self::getIni($tempDir);
            if (!isset($info['uid'])) {
                continue;
            }
            $installedList[] = $info;
        }
        return $installedList;
    }

    /**
     * 读取模块 info.ini
     */
    protected static function getIni(string $dir): array
    {
        $infoFile = $dir . 'info.ini';
        if (!is_file($infoFile)) {
            return [];
        }
        $info = @parse_ini_file($infoFile, true, INI_SCANNER_TYPED);
        return is_array($info) ? $info : [];
    }

    /**
     * 获取模块 Event 类命名空间（与 Server::getClass 逻辑一致）
     */
    protected static function getModuleEventClass(string $uid): ?string
    {
        $name = function_exists('parse_name') ? parse_name($uid) : str_replace('-', '_', $uid);
        $class = function_exists('parse_name') ? parse_name($name, 1) : ucfirst(str_replace('_', '', ucwords($name, '_')));
        $namespace = '\\modules\\' . $name . '\\' . $class;
        return class_exists($namespace) ? $namespace : null;
    }
}
