<?php
namespace EasyChat\Library\Support;

use EasyChat\Model\MessageContext;
use EasyChat\Model\Session;
use EasyChat\Model\Setting;







final class OfficialProductSupportProfile {
    private $registry;
    private $settings;

    public function __construct($registry) {
        $this->registry = $registry;
        $this->settings = (new Setting($registry))->getAll();
    }

    public function resolve(int $chat_id, int $message_id): ?array {
        if (!$this->isEnabledForCurrentInstallation()) return null;
        if (!$this->rolloutPolicy()->allows($chat_id)) return null;
        $session = (new Session($this->registry))->getSessionById($chat_id);
        if (!$session || strtolower((string)($session['source_provider'] ?? '')) !== 'widget') return null;

        return $this->buildProfile($chat_id, $message_id);
    }

     
    public function createQueueClaim(int $chat_id, int $message_id): string {
        if ($this->resolve($chat_id, $message_id) === null) return '';
        $secret = $this->installationSecret();
        if ($secret === '') return '';
        return hash_hmac('sha256', 'official_widget_queue|' . $chat_id . '|' . $message_id, $secret);
    }

    



    public function resolveQueueClaim(int $chat_id, int $message_id, string $claim): ?array {
        $secret = $this->installationSecret();
        if ($chat_id <= 0 || $message_id <= 0 || $secret === '' || trim($claim) === '') return null;
        $expected = hash_hmac('sha256', 'official_widget_queue|' . $chat_id . '|' . $message_id, $secret);
        if (!hash_equals($expected, trim($claim))) return null;
        $session = (new Session($this->registry))->getSessionById($chat_id);
        if (!$session || strtolower((string)($session['source_provider'] ?? '')) !== 'widget') return null;

        return $this->buildProfile($chat_id, $message_id);
    }

    private function buildProfile(int $chat_id, int $message_id): array {

        $route = '';
        $context_locale = '';
        $raw = (new MessageContext($this->registry))->getByMessageId($message_id, 'site_page');
        if ($raw) {
            $snapshot = json_decode((string)($raw['snapshot_json'] ?? ''), true);
            $page = is_array($snapshot) && is_array($snapshot['page'] ?? null) ? $snapshot['page'] : [];
            $url = (string)($page['canonical_url'] ?? $page['url'] ?? $raw['url'] ?? '');
            $path = parse_url($url, PHP_URL_PATH);
            $route = is_string($path) ? trim($path, '/') : '';
            $route = preg_match('/^[a-zA-Z0-9_\/-]{0,160}$/D', $route) === 1 ? $route : '';
            $context_locale = is_array($snapshot) && (string)($snapshot['locale'] ?? '') === 'en' ? 'en' : '';
        }

        $locale = $context_locale !== ''
            ? $context_locale
            : (strtolower((string)($this->settings['chat_widget_locale'] ?? 'ru')) === 'en' ? 'en' : 'ru');
        $platform = strtolower(trim((string)($this->settings['chat_cms_type'] ?? 'generic')));
        if (preg_match('/^[a-z0-9_-]{1,40}$/D', $platform) !== 1) $platform = 'generic';
        return [
             
             
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'profile' => 'easychat_product_support',
            'space' => 'official_easychat_docs',
            'locale' => $locale,
            'product_version' => defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '',
            'platform' => $platform,
            'route' => $route,
        ];
    }

    private function installationSecret(): string {
        $secret = trim((string)($this->settings['chat_install_secret'] ?? ''));
        if ($secret === '') $secret = trim((string)($this->settings['chat_app_master_token'] ?? ''));
        return $secret;
    }

    public function isEnabledForCurrentInstallation(): bool {
        return $this->enabled() && $this->officialHost() && $this->rolloutPolicy()->hasAudience();
    }

    public function hasServiceCredential(): bool {
        if (trim((string)($this->settings['chat_easytokens_support_key'] ?? '')) !== '') return true;
        return strtolower(trim((string)($this->settings['chat_ai_provider'] ?? ''))) === 'easytokens'
            && trim((string)($this->settings['chat_ai_key'] ?? '')) !== '';
    }

    private function enabled(): bool {
        return OfficialSupportRuntimeConfig::enabled('EASYCHAT_PRODUCT_SUPPORT_ENABLED');
    }

    private function rolloutPolicy(): OfficialSupportRolloutPolicy {
        return new OfficialSupportRolloutPolicy(
            OfficialSupportRuntimeConfig::value('EASYCHAT_PRODUCT_SUPPORT_ROLLOUT_PERCENT'),
            $this->installationSecret()
        );
    }

    private function officialHost(): bool {
        $configured = OfficialSupportRuntimeConfig::value('EASYCHAT_PRODUCT_SUPPORT_HOSTS');
        $allowed = $configured !== '' ? preg_split('/[\s,]+/', strtolower($configured)) : ['easychat24.ru', 'www.easychat24.ru'];
        $allowed = array_values(array_filter(array_map(function ($host) {
            return preg_match('/^[a-z0-9.-]+$/D', (string)$host) === 1 ? trim((string)$host, '.') : '';
        }, $allowed)));
        $host = strtolower((string)parse_url(defined('HTTP_SERVER') ? HTTP_SERVER : '', PHP_URL_HOST));
        return $host !== '' && in_array($host, $allowed, true);
    }
}
