<?php
namespace EasyChat\Library\Support;

use EasyChat\Model\Setting;
use EasyChat\Library\Queue\SchedulerHealthService;

 
final class AdminHelpContextBuilder {
    private const ROUTES = [
        'index', 'quickreply', 'operator', 'analytics', 'notification_health',
        'knowledge_storage', 'integration', 'marketplace', 'setting', 'update',
    ];

    private $settings;

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

    public function build(string $route, string $locale, bool $with_diagnostics = false): array {
        $route = strtolower(trim($route));
        $route = in_array($route, self::ROUTES, true) ? $route : 'index';
        $context = [
            'product_version' => defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : 'unknown',
            'platform' => $this->platform(),
            'platform_version' => $this->platformVersion(),
            'locale' => $locale === 'en' ? 'en' : 'ru',
            'route' => $route,
            'enabled_features' => $this->enabledFeatures(),
        ];
        if ($with_diagnostics) {
            $context['diagnostics'] = $this->diagnostics();
        }
        return $context;
    }

    public function disclosure(string $locale = 'ru'): array {
        if ($locale === 'en') {
            return [
                'EasyChat version, CMS type and available CMS version',
                'Current admin section',
                'Names of enabled features',
                'Safe status codes without logs or conversations',
            ];
        }
        return [
            'Версия EasyChat, тип и доступная версия CMS',
            'Текущий раздел админки',
            'Названия включённых функций',
            'Безопасные коды состояния без логов и переписки',
        ];
    }

    private function platform(): string {
        $value = strtolower(trim((string)($this->settings['chat_cms_type'] ?? 'none')));
        return preg_match('/^[a-z0-9_-]{1,40}$/D', $value) === 1 ? $value : 'generic';
    }

    





    private function platformVersion(): string {
        $platform = $this->platform();
        $candidates = [];

        if ($platform === 'wordpress' && function_exists('get_bloginfo')) {
            $candidates[] = (string)get_bloginfo('version');
        } elseif ($platform === 'bitrix' && defined('SM_VERSION')) {
            $candidates[] = (string)SM_VERSION;
        } elseif ($platform === 'opencart' && defined('VERSION')) {
            $legacy = (string)VERSION;
            $easychat = defined('EASYCHAT_VERSION') ? (string)EASYCHAT_VERSION : '';
            if ($legacy !== $easychat) $candidates[] = $legacy;
        }

         
         
        $candidates[] = (string)($this->settings['chat_host_cms_version'] ?? '');
        foreach ($candidates as $candidate) {
            $candidate = trim($candidate);
            if ($candidate !== '' && preg_match('/^[0-9][0-9A-Za-z._+-]{0,39}$/D', $candidate) === 1) {
                return $candidate;
            }
        }
        return 'unknown';
    }

    private function enabledFeatures(): array {
        $map = [
            'chat_ai_status' => 'ai_auto_replies',
            'chat_ai_suggestions_status' => 'ai_suggestions',
            'chat_cms_catalog_status' => 'catalog',
            'chat_cms_search_status' => 'smart_search',
            'chat_webpush_status' => 'webpush',
            'chat_max_personal_status' => 'personal_max',
            'chat_whatsapp_personal_status' => 'personal_whatsapp',
            'chat_telegram_status' => 'telegram',
            'chat_vk_status' => 'vk',
            'chat_avito_status' => 'avito',
        ];
        $result = [];
        foreach ($map as $key => $label) {
            if ((string)($this->settings[$key] ?? '0') === '1') $result[] = $label;
        }
        sort($result);
        return array_slice($result, 0, 16);
    }

    private function diagnostics(): array {
        $php_version = preg_match('/^\d+\.\d+\.\d+/', PHP_VERSION, $match) ? $match[0] : 'unknown';
        return [
            'php_version' => $php_version,
            'php_sapi' => PHP_SAPI === 'cli' ? 'cli' : 'web',
            'extensions' => [
                'curl' => extension_loaded('curl'),
                'json' => extension_loaded('json'),
                'openssl' => extension_loaded('openssl'),
                'mbstring' => extension_loaded('mbstring'),
            ],
            'ai_key_configured' => trim((string)($this->settings['chat_easytokens_support_key'] ?? '')) !== ''
                || (
                    strtolower(trim((string)($this->settings['chat_ai_provider'] ?? ''))) === 'easytokens'
                    && trim((string)($this->settings['chat_ai_key'] ?? '')) !== ''
                ),
            'scheduler' => $this->schedulerState(),
        ];
    }

    private function schedulerState(): array {
        $state = SchedulerHealthService::state($this->settings);
        $age = isset($state['age_seconds']) ? max(0, (int)$state['age_seconds']) : null;
        return [
            'status' => (string)($state['status'] ?? 'waiting'),
            'age_bucket' => $age === null ? 'unknown' : ($age <= 180 ? 'recent' : ($age <= 900 ? 'delayed' : 'stale')),
            'runner' => (string)($state['runner'] ?? ''),
            'error_code' => (string)($state['error_code'] ?? ''),
        ];
    }
}
