<?php
namespace EasyChat\Library\Support;





final class OfficialCommercialGroundingPolicy {
    public function normalize($value): array {
        $value = is_array($value) ? $value : [];
        $sources = [];
        foreach (array_slice(is_array($value['sources'] ?? null) ? $value['sources'] : [], 0, 1) as $source) {
            if (!is_array($source) || (int)($source['id'] ?? 0) !== 1) continue;
            $url = trim((string)($source['url'] ?? ''));
            if (!$this->isCanonicalPricingUrl($url)) continue;
            $sources[] = [
                'id' => 'S1',
                'title' => $this->limit((string)($source['title'] ?? 'Цены EasyChat'), 160),
                'url' => OfficialCommercialQueryPolicy::PRICING_URL,
                'section' => '',
                'locale' => 'ru',
            ];
        }
        return [
            'status' => !empty($value['web_used']) && $sources ? 'grounded' : 'unavailable',
            'confidence' => !empty($value['web_used']) && $sources ? 1.0 : 0.0,
            'sources' => $sources,
            'clarification' => '',
            'reason' => !empty($value['web_used']) ? '' : 'pricing_web_evidence_missing',
        ];
    }

    public function finalize(string $model_answer, array $grounding, string $locale): array {
        $locale = $locale === 'en' ? 'en' : 'ru';
        if (($grounding['status'] ?? '') !== 'grounded' || empty($grounding['sources'])) {
            $grounding['status'] = 'handoff';
            $grounding['sources'] = [];
            return ['answer' => $this->unverifiedAnswer($locale), 'grounding' => $grounding];
        }
        $has_citation = false;
        $answer = preg_replace_callback('/\[(\d{1,2})\]/', function ($match) use (&$has_citation) {
            if ($match[1] === '1') {
                $has_citation = true;
                return '[S1]';
            }
            return '';
        }, $model_answer);
        $answer = preg_replace('/\[([^\]]+)\]\(https?:\/\/[^)\s]+\)/i', '$1', (string)$answer);
        $answer = preg_replace('/https?:\/\/[^\s<>()]+/i', '', (string)$answer);
        $answer = trim($this->limit((string)$answer, 4000));
        if (!$has_citation || $answer === '') {
            $grounding['status'] = 'handoff';
            $grounding['sources'] = [];
            $grounding['reason'] = 'pricing_citation_contract_invalid';
            return ['answer' => $this->unverifiedAnswer($locale), 'grounding' => $grounding];
        }
        return ['answer' => \EasyChat\Library\MessageTextRenderer::withoutCitationMarkers($answer), 'grounding' => $grounding];
    }

    private function isCanonicalPricingUrl(string $url): bool {
        $parts = parse_url($url);
        return is_array($parts)
            && strtolower((string)($parts['scheme'] ?? '')) === 'https'
            && strtolower((string)($parts['host'] ?? '')) === 'easychat24.ru'
            && in_array((string)($parts['path'] ?? ''), ['/pricing', '/pricing/'], true)
            && !isset($parts['user'], $parts['pass'], $parts['port'], $parts['query'], $parts['fragment']);
    }

    private function unverifiedAnswer(string $locale): string {
        return $locale === 'en'
            ? 'I could not verify the current EasyChat price on the official pricing page. Please open the pricing page or contact support.'
            : 'Не удалось подтвердить актуальную цену на официальной странице EasyChat. Откройте страницу цен или обратитесь в поддержку.';
    }

    private function limit(string $value, int $length): string {
        return mb_substr(trim($value), 0, $length, 'UTF-8');
    }
}
