<?php
namespace EasyChat\Library\Support;






final class OfficialCommercialQueryPolicy {
    public const PRICING_URL = 'https://easychat24.ru/pricing/';

    public function isCommercialQuestion(string $question): bool {
        $question = mb_strtolower(trim($question), 'UTF-8');
        if ($question === '') {
            return false;
        }
        return preg_match('/(?:сколько\s+стоит|цен[аы]|стоимост|тариф|прайс|подписк|лицензи|купить|оплат|бесплатн\w*\s+(?:период|проб\w*)|price|pricing|cost|subscription|license|free\s+(?:trial|period))/u', $question) === 1;
    }

    








    public function isCommercialConversation(string $question, array $history): bool {
        if ($this->isCommercialQuestion($question)) return true;
        $question = mb_strtolower(trim($question), 'UTF-8');
        if (
            $question === ''
            || (function_exists('mb_strlen') ? \mb_strlen($question, 'UTF-8') : strlen($question)) > 120
            || preg_match('/(?:есть\s+ли|существу\w*|доступ\w*|поддержива\w*|имеется).{0,60}(?:модул\w*|плагин\w*|верс\w*|пакет\w*|интеграц\w*)|(?:модул\w*|плагин\w*|интеграц\w*).{0,60}(?:для|под)/u', $question)
        ) return false;
        foreach (array_reverse(array_slice($history, -4)) as $message) {
            if (!is_array($message)) continue;
            $content = $message['content'] ?? '';
            if (!is_string($content)) continue;
            $content = mb_strtolower(trim($content), 'UTF-8');
            if ($content === $question) continue;
            if ($this->isCommercialQuestion($content) || preg_match('/\b\d[\d\s]{2,}\s*(?:₽|руб|rub)\b/u', $content)) return true;
        }
        return false;
    }

    public function webPayload(): array {
        return [
            'enabled' => 'always',
            'scope' => 'url_only',
            'mode' => 'grounded',
            'provider' => 'default',
            'urls' => [self::PRICING_URL],
            'include_domains' => ['easychat24.ru'],
            'max_sources' => 1,
            'return_sources' => true,
        ];
    }
}
