<?php

declare(strict_types=1);

namespace LolaCore\Chat;

/**
 * Detects when the model verbalizes intent ("let me look that up") without tool calls.
 */
final class IntentDeferralDetector
{
    /**
     * @var list<string>
     */
    private const DEFERRAL_PATTERNS = [
        '/\b(déjame|permíteme|deja que|voy a|ahora voy a|primero voy a)\b/ui',
        '/\b(voy a obtener|voy a buscar|voy a revisar|voy a comprobar|obtener sus datos)\b/ui',
        '/\b(necesito (obtener|buscar|revisar|comprobar|consultar))\b/ui',
        '/\b(deixa eu|deixa que eu|vou (verificar|buscar|revisar|consultar|obter))\b/ui',
        '/\b(preciso (obter|buscar|revisar|consultar|verificar))\b/ui',
        '/\b(let me|allow me to|i need to (get|check|look|fetch|retrieve|inspect))\b/ui',
        "/\b(i['']ll|i will)\s+(get|check|look|fetch|retrieve|inspect|obtain)\b/ui",
    ];

    /**
     * @var list<string>
     */
    private const SHORT_CONFIRMATIONS = [
        'ok',
        'okay',
        'yes',
        'yep',
        'yeah',
        'si',
        'sí',
        'vale',
        'adelante',
        'continua',
        'continúa',
        'sim',
        'beleza',
        'pode ser',
        'obrigado',
        'obrigada',
        'pode ir',
        'go ahead',
        'sure',
        'thanks',
        'thank you',
        'gracias',
    ];

    public static function isDeferredIntentResponse(string $assistantContent): bool
    {
        $text = trim($assistantContent);
        if ($text === '') {
            return false;
        }

        foreach (self::DEFERRAL_PATTERNS as $pattern) {
            if (preg_match($pattern, $text) === 1) {
                return true;
            }
        }

        return false;
    }

    public static function isActionableUserRequest(?string $userMessage): bool
    {
        if ($userMessage === null) {
            return false;
        }

        $text = trim($userMessage);
        if ($text === '' || str_starts_with($text, '__')) {
            return false;
        }

        $lower = strtolower($text);
        if (in_array($lower, self::SHORT_CONFIRMATIONS, true)) {
            return false;
        }

        return true;
    }

    public static function shouldAutoContinue(?string $userMessage, string $assistantContent): bool
    {
        return self::isActionableUserRequest($userMessage)
            && self::isDeferredIntentResponse($assistantContent);
    }
}
