<?php

declare(strict_types=1);

namespace BotGuard\Services\Detection\Modules;

use BotGuard\Services\Detection\ModuleResult;
use BotGuard\Services\Detection\SignalBag;

/**
 * Honeypot module.
 *
 * The verification page renders invisible fields that a human never sees or
 * fills. Bots that blindly complete every input trip these traps. We also check
 * a "time trap": a hidden timestamp field the client echoes back — a form
 * submitted implausibly fast after render is bot-like.
 */
final class HoneypotModule extends AbstractModule
{
    public function key(): string
    {
        return 'honeypot';
    }

    public function analyze(SignalBag $signals): ModuleResult
    {
        $hp = $signals->clientArray('honeypot');

        // Two decoy fields that must remain empty, plus a render-to-submit delay.
        $decoyEmail = trim((string) ($hp['contact_email'] ?? ''));   // CSS-hidden text input
        $decoyUrl = trim((string) ($hp['website'] ?? ''));           // off-screen input
        $renderDelayMs = (int) ($hp['render_delay_ms'] ?? 9999);

        $this->detail('decoy_email_filled', $decoyEmail !== '');
        $this->detail('decoy_url_filled', $decoyUrl !== '');
        $this->detail('render_delay_ms', $renderDelayMs);

        // Filling either hidden field is a strong bot signal.
        $this->check('Hidden email decoy empty', $decoyEmail === '', 3.0);
        $this->check('Hidden URL decoy empty', $decoyUrl === '', 3.0);

        // A form completed within ~500ms of render is not human.
        $this->check('Render-to-submit delay plausible', $renderDelayMs >= 500, 2.0);

        return $this->result();
    }
}
