<?php

namespace Application\Service\Extension\Helper;

class DocumentHelper
{
    private const SUPPORT_TAGS = [
        'actionUrl' => '/@actionUrl (.*)/',
        'analysis' => '/@analysis (.*)/',
    ];

    private static array $tagsContainer = [];

//    private static array $tagsCache = [];

    /**
     * 初始化注解
     * @param string $documentString
     */
    public static function load(string $documentString)
    {
        foreach (self::SUPPORT_TAGS as $tagName => $rules) {
            preg_match($rules, $documentString, $matches);
            if ($matches) {
                self::$tagsContainer[$tagName] = trim($matches[1]);
                if (SDMHelper::app()->exist($tagName) && method_exists(SDMHelper::app()->{$tagName}, 'init')) {
                    SDMHelper::app()->{$tagName}->init(self::getTag($tagName));
                }
            }
        }
    }

    public static function getTag(string $tagString)
    {
        if ($tagString === 'analysis') {
            if (is_array(self::$tagsContainer[$tagString])) {
                return self::$tagsContainer[$tagString];
            }

            // 匹配 TIMES 和 RESPONSE_TIME[max=200] 的正则表达式
            preg_match_all('/([A-Z_]+)(\[(.*?)\])?/', self::$tagsContainer[$tagString], $matches, PREG_SET_ORDER);
            // 结果数组
            $result = [];

            foreach ($matches as $match) {
                $key = $match[1]; // TIMES 或 RESPONSE_TIME
                if (isset($match[3])) {
                    // 如果有 [max=200] 格式，解析为关联数组
                    parse_str(str_replace(['=', '[', ']'], ['=', '&', ''], $match[3]), $params);
                    $result[$key] = $params;
                } else {
                    $result[$key] = null; // 只有 TIMES 没有参数
                }
            }

            self::$tagsContainer[$tagString] = $result;
        }

        return self::$tagsContainer[$tagString];
    }
}