<?php
namespace EasyChat\Library\Catalog;

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








class CatalogIndexScheduler {

    const DEFAULT_INTERVAL = 86400;
    const SCHEDULE_GUARD_INTERVAL = 3600;
    const DEDUPE_KEY = 'catalog_full_index';

     
    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function enqueueIfDue(int $interval = self::DEFAULT_INTERVAL): array {
        $settings_model = new Setting($this->registry);
        $settings = $settings_model->getAll();
        $enabled = (string)($settings['chat_cms_semantic_enabled'] ?? '0') === '1';
        $has_sources = (string)($settings['chat_cms_index_products'] ?? '0') === '1'
            || (string)($settings['chat_cms_index_pages'] ?? '0') === '1';

        if (!$enabled || !$has_sources) {
            return $this->result(false, 0, 'disabled');
        }

        $now = time();
        $last_completed = $this->timestamp($settings['chat_cms_last_indexed_at'] ?? '');
        if ($last_completed > 0 && ($now - $last_completed) < max(3600, $interval)) {
            return $this->result(false, 0, 'not_due');
        }

         
         
        $last_scheduled = $this->timestamp($settings['chat_cms_last_index_scheduled_at'] ?? '');
        if ($last_scheduled > 0 && ($now - $last_scheduled) < self::SCHEDULE_GUARD_INTERVAL) {
            return $this->result(false, 0, 'already_scheduled');
        }

        $job_id = (new QueueManager($this->registry))->pushUnique(
            'cms_index',
            array(
                'reason' => 'scheduled',
                'source_signature' => self::sourceSignature($settings),
            ),
            self::DEDUPE_KEY,
            0,
            10
        );
        $settings_model->set('chat_cms_last_index_scheduled_at', date('c', $now));

        return $this->result(true, $job_id, 'queued');
    }

    



    public static function sourceSignature(array $settings): string {
        $fields = array(
            'chat_cms_type',
            'chat_cms_prefix',
            'chat_cms_index_products',
            'chat_cms_index_pages',
            'chat_embedding_use_name',
            'chat_embedding_use_desc',
            'chat_embedding_use_attrs',
            'chat_embedding_use_options',
            'chat_embedding_use_model',
            'chat_embedding_use_sku',
        );
        $parts = array();
        foreach ($fields as $field) {
            $parts[] = $field . '=' . trim((string)($settings[$field] ?? ''));
        }
        return substr(hash('sha256', implode("\n", $parts)), 0, 16);
    }

    public static function firstEnabledSource(array $settings): string {
        return (string)($settings['chat_cms_index_products'] ?? '0') === '1'
            ? 'products'
            : 'pages';
    }

    private function timestamp($value): int {
        $value = trim((string)$value);
        if ($value === '') {
            return 0;
        }
        $timestamp = strtotime($value);
        return $timestamp === false ? 0 : (int)$timestamp;
    }

    private function result(bool $queued, int $job_id, string $reason): array {
        return array(
            'ran' => $queued,
            'queued' => $queued ? 1 : 0,
            'job_id' => $job_id,
            'reason' => $reason,
        );
    }
}
