<?php
namespace EasyChat\Library\Catalog;

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

 
class CatalogSemanticBootstrap {

    public const SEARCH_AUTO_OPT_OUT_KEY = 'chat_cms_search_auto_opt_out';

    




    public static function applyCatalogChoice(array $previous, array $next): array {
        $search_enabled = (int)($next['chat_productsearch'] ?? 0) > 0;
        $semantic_enabled = $search_enabled
            && (string)($next['chat_cms_semantic_enabled'] ?? '0') === '1';

        $next[self::SEARCH_AUTO_OPT_OUT_KEY] = $search_enabled ? '0' : '1';
        if (!$search_enabled) {
            $next['chat_productsearch'] = '0';
            $next['chat_cms_semantic_enabled'] = '0';
            $next['chat_cms_index_products'] = '0';
            $next['chat_cms_index_pages'] = '0';
            $next['chat_cms_semantic_auto_opt_out'] = '1';
            $next['chat_cms_last_index_scheduled_at'] = '';
            return $next;
        }

        $next['chat_productsearch'] = $semantic_enabled ? '3' : '2';
        if ($semantic_enabled) {
            $next['chat_cms_semantic_enabled'] = '1';
            $next['chat_cms_index_products'] = '1';
            $next['chat_cms_semantic_auto_opt_out'] = '0';
        } else {
            $next['chat_cms_semantic_enabled'] = '0';
            $next['chat_cms_index_products'] = '0';
            $next['chat_cms_index_pages'] = '0';
            $next['chat_cms_semantic_auto_opt_out'] = (string)($previous['chat_cms_semantic_auto_opt_out'] ?? '0') === '1'
                ? '1'
                : '0';
        }

        return $next;
    }

     
    public static function becameAiReady(array $previous, array $next): bool {
        $next_ready = (string)($next['chat_ai_status'] ?? '0') === '1'
            && trim((string)($next['chat_ai_key'] ?? '')) !== '';
        if (!$next_ready) {
            return false;
        }

        return (string)($previous['chat_ai_status'] ?? '0') !== '1'
            || trim((string)($previous['chat_ai_key'] ?? '')) === '';
    }

    




    public static function planIfReady($registry, array $settings, string $reason = 'ai_onboarding'): array {
        if ((string)($settings[self::SEARCH_AUTO_OPT_OUT_KEY] ?? '0') === '1') {
            return array('enabled' => false, 'reason' => 'search_opted_out', 'updates' => array());
        }
        if ((string)($settings['chat_cms_semantic_auto_opt_out'] ?? '0') === '1') {
            return array('enabled' => false, 'reason' => 'opted_out', 'updates' => array());
        }
        if ((string)($settings['chat_cms_semantic_enabled'] ?? '0') === '1'
            && (string)($settings['chat_cms_index_products'] ?? '0') === '1') {
            return array('enabled' => true, 'reason' => 'already_enabled', 'updates' => array());
        }
        if ((string)($settings['chat_ai_status'] ?? '0') !== '1' || trim((string)($settings['chat_ai_key'] ?? '')) === '') {
            return array('enabled' => false, 'reason' => 'ai_not_ready', 'updates' => array());
        }

        $edition = defined('EASYCHAT_CMS_EDITION') ? (string)EASYCHAT_CMS_EDITION : '';
        $connection = CmsCatalogConnectionResolver::resolve($registry->get('db'), $settings, $edition);
        if (empty($connection['ready'])) {
            return array('enabled' => false, 'reason' => 'catalog_not_ready', 'updates' => array());
        }

        $updates = array(
            'chat_cms_type' => $connection['type'],
            'chat_cms_prefix' => $connection['prefix'],
            'chat_productsearch' => '3',
            'chat_cms_semantic_enabled' => '1',
            'chat_cms_index_products' => '1',
            'chat_cms_index_pages' => '0',
            'chat_cms_semantic_auto_enabled' => '1',
            'chat_cms_semantic_auto_opt_out' => '0',
            self::SEARCH_AUTO_OPT_OUT_KEY => '0',
            'chat_cms_last_index_scheduled_at' => date('c'),
        );

        return array(
            'enabled' => true,
            'reason' => 'enabled',
            'queue_reason' => $reason,
            'updates' => $updates,
            'settings' => array_merge($settings, $updates),
        );
    }

    public static function publicState(array $settings): array {
        $mode = in_array((string)($settings['chat_productsearch'] ?? '0'), array('1', '2', '3'), true)
            ? (string)$settings['chat_productsearch']
            : '0';
        return array(
            'mode' => $mode,
            'search_enabled' => $mode !== '0',
            'semantic_enabled' => (string)($settings['chat_cms_semantic_enabled'] ?? '0') === '1'
                && in_array($mode, array('1', '3'), true),
            'index_products' => (string)($settings['chat_cms_index_products'] ?? '0') === '1',
            'index_pages' => (string)($settings['chat_cms_index_pages'] ?? '0') === '1',
        );
    }

    public static function enableIfReady($registry, string $reason = 'ai_onboarding'): array {
        $model = new Setting($registry);
        $settings = $model->getAll();
        $plan = self::planIfReady($registry, $settings, $reason);
        if (empty($plan['updates'])) {
            return array(
                'enabled' => !empty($plan['enabled']),
                'reason' => (string)($plan['reason'] ?? 'not_ready'),
            );
        }

         
         
        $queue = new QueueManager($registry);
        $job_id = 0;
        $model->setManyAtomic((array)$plan['updates'], function () use ($queue, $plan, &$job_id): void {
            $effective = (array)($plan['settings'] ?? array());
            $job_id = $queue->pushUnique(
                'cms_index',
                array(
                    'reason' => (string)($plan['queue_reason'] ?? 'ai_onboarding'),
                    'source_signature' => CatalogIndexScheduler::sourceSignature($effective),
                ),
                CatalogIndexScheduler::DEDUPE_KEY,
                0,
                10
            );
        });
        return array('enabled' => true, 'reason' => 'enabled', 'job_id' => $job_id);
    }
}
