<?php
namespace EasyChat\Library\Support;

 
final class AdminHelpHandoffPolicy {
    public function evaluate(string $question, string $grounding_status, float $confidence, int $unresolved_count): array {
        if (!$this->enabled()) {
            return ['show' => false, 'reason' => 'disabled', 'telegram_url' => '', 'max_url' => ''];
        }
        $question = mb_strtolower($question, 'UTF-8');
        $asks_human = preg_match('/(?:человек|оператор|поддержк|живой|human|support agent)/u', $question) === 1;
        $private_case = $this->asksForPrivateData($question);
        $knowledge_handoff = in_array($grounding_status, ['handoff', 'unavailable'], true);
        $repeated_unresolved = $grounding_status !== 'grounded' && $unresolved_count >= 2;

         
         
         
         
         
        $required = $asks_human
            || $private_case
            || $knowledge_handoff
            || $repeated_unresolved;
        $telegram_url = $required ? $this->supportUrl(
            'EASYCHAT_SUPPORT_TELEGRAM_URL',
            'https://t.me/easychat24_support',
            't.me'
        ) : '';
        $max_url = $required ? $this->supportUrl(
            'EASYCHAT_SUPPORT_MAX_URL',
            'https://max.ru/join/k50gnE1X8NVzvuE2pAY4DThceZg00BVITThogZBntyk',
            'max.ru'
        ) : '';
        return [
            'show' => $required,
            'reason' => $asks_human
                ? 'human_requested'
                : ($private_case
                    ? 'private_diagnostics_required'
                    : ($repeated_unresolved
                        ? 'unresolved_twice'
                        : ($knowledge_handoff ? 'knowledge_unavailable' : 'not_required'))),
            'telegram_url' => $telegram_url,
            'max_url' => $max_url,
        ];
    }

    private function asksForPrivateData(string $question): bool {
         
         
         
         
        $secret_extraction = preg_match(
            '/(?:покаж|раскр|вывед|пришл|назов|скопир|дай|reveal|show|send|return).{0,48}(?:парол|api[ _-]?key|ключ|token|токен|secret|секрет)/u',
            $question
        ) === 1;
        $private_installation = preg_match(
            '/(?:мо(?:я|ей|его|й)|эт(?:а|ой|ого|у)|конкретн\S*).{0,28}(?:установк|сервер|магазин|лог|диагностик)/u',
            $question
        ) === 1 || preg_match(
            '/(?:установк|сервер|магазин|лог|диагностик).{0,28}(?:мо(?:я|ей|его|й)|эт(?:а|ой|ого|у)|конкретн\S*)/u',
            $question
        ) === 1 || preg_match(
            '/(?:my|this|specific).{0,28}(?:installation|server|store|logs?|diagnostic)/u',
            $question
        ) === 1;
        $private_account = preg_match(
            '/(?:мо(?:я|ей|его|й)|эт(?:а|ой|ого|у)|конкретн\S*).{0,20}(?:лицензи|плат[её]ж|оплат|сч[её]т)/u',
            $question
        ) === 1 || preg_match(
            '/(?:лицензи|плат[её]ж|оплат|сч[её]т).{0,20}(?:мо(?:я|ей|его|й)|эт(?:а|ой|ого|у)|конкретн\S*)/u',
            $question
        ) === 1 || preg_match(
            '/(?:my|this|specific).{0,20}(?:licen[cs]e|payment|invoice|account)/u',
            $question
        ) === 1;
        return $secret_extraction || $private_installation || $private_account;
    }

    private function enabled(): bool {
        $value = strtolower(OfficialSupportRuntimeConfig::value('EASYCHAT_SUPPORT_HANDOFF_ENABLED'));
         
         
        if ($value === '') return true;
        return in_array($value, ['1', 'true', 'yes', 'on'], true);
    }

    private function supportUrl(string $env_name, string $fallback, string $host): string {
        $url = OfficialSupportRuntimeConfig::value($env_name);
        if ($url === '') $url = $fallback;
        $parts = parse_url($url);
        if (
            !is_array($parts)
            || strtolower((string)($parts['scheme'] ?? '')) !== 'https'
            || strtolower((string)($parts['host'] ?? '')) !== $host
            || isset($parts['user'])
            || isset($parts['pass'])
        ) {
            return '';
        }
        return $url;
    }
}
