<?php
/**
 * 判定理由辅助
 */

if (!function_exists('cloak_reason_append')) {
    function cloak_reason_append($reason, $suffix)
    {
        $reason = trim((string) $reason);
        $suffix = trim((string) $suffix);
        if ($suffix === '') {
            return $reason;
        }
        if ($reason === '') {
            return $suffix;
        }
        if (strpos($reason, $suffix) !== false) {
            return $reason;
        }
        return $reason . '；' . $suffix;
    }
}

if (!function_exists('cloak_reason_or')) {
    function cloak_reason_or($reason, $fallback)
    {
        $reason = trim((string) $reason);
        return $reason !== '' ? $reason : (string) $fallback;
    }
}

if (!function_exists('cloak_api_reason')) {
    function cloak_api_reason(array $return, $checkResult)
    {
        $reason = trim((string) ($return['reason'] ?? ''));
        if ($reason !== '') {
            return $reason;
        }
        $pass = ($checkResult === 'true' || $checkResult === true || !empty($return['result']));
        return $pass ? 'API判定通过' : 'API判定拒绝';
    }
}

if (!function_exists('cloak_cache_hit_log_reason')) {
    /**
     * 缓存判定落库 reason：true 为空；false 固定为「缓存」。
     *
     * @param string $result
     */
    function cloak_cache_hit_log_reason($result)
    {
        return cloak_normalize_log_reason((string) $result, (string) $result === 'true' ? '' : '缓存');
    }
}

if (!function_exists('cloak_normalize_log_reason')) {
    /**
     * 落库 reason 规范化：true 必须为空；false 必须有值；wait 保留检测中文案。
     *
     * @param string $result
     * @param mixed  $reason
     */
    function cloak_normalize_log_reason($result, $reason)
    {
        $result = (string) $result;
        $reason = trim((string) $reason);

        if ($result === 'true') {
            return '';
        }
        if ($result === 'wait') {
            return $reason !== '' ? $reason : '二次风控检测中';
        }
        if ($reason === '') {
            return '判定拒绝(安全页)';
        }
        return $reason;
    }
}

if (!function_exists('cloak_finalize_reason')) {
    function cloak_finalize_reason($reason, $checkResult)
    {
        $result = ($checkResult === 'true') ? 'true' : (($checkResult === 'false') ? 'false' : (string) $checkResult);
        return cloak_normalize_log_reason($result, $reason);
    }
}
