<?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;

        $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,
            'profile' => 'easychat_product_support',
            'space' => 'official_easychat_docs',
            'locale' => $locale,
            'product_version' => defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '',
            'platform' => $platform,
            'route' => $route,
        ];
    }

    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 {
        $secret = trim((string)($this->settings['chat_install_secret'] ?? ''));
        if ($secret === '') $secret = trim((string)($this->settings['chat_app_master_token'] ?? ''));
        return new OfficialSupportRolloutPolicy(
            OfficialSupportRuntimeConfig::value('EASYCHAT_PRODUCT_SUPPORT_ROLLOUT_PERCENT'),
            $secret
        );
    }

    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);
    }
}
