<?php

namespace ZenoChatbot\Services;

use ZenoChatbot\Helper\Settings;
use ZenoChatbot\Services\Scheduler\Scheduler;
use ZenoChatbot\Support\Hooks;

if (!defined('ABSPATH')) {
    exit;
}

class ConversationSummaryWatcher
{
    public const FIVE_MINUTE_SCHEDULE = 'zeno_chatbot_ai_every_five_minutes';

    public static function handleSummaryRequested($payload = []): void
    {
        if (!is_array($payload)) {
            return;
        }

        $conversationId = absint($payload['conversation_id'] ?? 0);
        if ($conversationId <= 0) {
            return;
        }

        $trigger = sanitize_key((string) ($payload['trigger'] ?? 'system'));
        if (!in_array($trigger, ['auto_close', 'user_close', 'admin_close'], true)) {
            return;
        }

        $autoSummaryEnabled = (string) (Settings::getChatSettings()['auto_summary_enabled'] ?? 'yes') === 'yes';
        if (!$autoSummaryEnabled) {
            return;
        }

        ConversationLifecycleService::markSummaryPending($conversationId);

        Scheduler::schedule(Hooks::CONVERSATION_PROCESS_SUMMARY, [static::class, 'runProcessJob'])
            ->group(Scheduler::defaultGroup())
            ->args([
                'conversation_id' => $conversationId,
                'trigger' => $trigger,
            ])
            ->unique()
            ->after(1)
            ->dispatch();
    }

    public static function runProcessJob($payload = []): void
    {
        $payload = is_array($payload) ? $payload : [];
        $conversationId = absint($payload['conversation_id'] ?? 0);
        $trigger = sanitize_key((string) ($payload['trigger'] ?? 'system'));
        static::processSummaryEvent($conversationId, $trigger);
    }

    public static function processSummaryEvent($conversationId, $trigger = 'system'): void
    {
        $conversationId = absint($conversationId);
        if ($conversationId <= 0) {
            return;
        }

        $trigger = sanitize_key((string) $trigger);
        $force = in_array($trigger, ['retry', 'regenerate'], true);

        ConversationLifecycleService::processSummaryGeneration($conversationId, $trigger, $force);
    }

    public static function runMaintenance(): void
    {
        ConversationLifecycleService::processAutoCloseBatch();
    }

    public static function runMaintenanceJob($payload = []): void
    {
        static::runMaintenance();
    }

    public static function ensureMaintenanceScheduled(): void
    {
        Scheduler::sync(Hooks::CONVERSATION_MAINTENANCE, [static::class, 'runMaintenanceJob'])
            ->group(Scheduler::defaultGroup())
            ->repeat()
            ->on('PT5M')
            ->unique()
            ->dispatch();
    }
}
