<?php

declare(strict_types=1);

namespace BotGuard\Services\Detection\Modules;

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

/**
 * Scroll-behaviour analysis module.
 *
 * Humans scroll in bursts with variable speed and occasional direction changes
 * and pauses. A page consumed with zero scrolling, or scrolled in a single
 * perfectly uniform sweep, is bot-like. Short pages that need no scroll make
 * absence neutral.
 */
final class ScrollModule extends AbstractModule
{
    public function key(): string
    {
        return 'scroll';
    }

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

        if ($scroll === []) {
            return $this->scored(0.55, [], [], ['present' => false]);
        }

        $events = (int) ($scroll['event_count'] ?? 0);
        $distance = (float) ($scroll['total_distance'] ?? 0);
        $speedStd = (float) ($scroll['speed_stddev'] ?? 0);
        $directionChanges = (int) ($scroll['direction_changes'] ?? 0);
        $dwellMs = (int) ($scroll['dwell_ms'] ?? 0);

        $this->detail('event_count', $events);
        $this->detail('total_distance', $distance);
        $this->detail('direction_changes', $directionChanges);

        // Any genuine scroll activity.
        $this->check('Scroll activity present', $events >= 2, 1.0);

        // Variable scroll speed (momentum/burst behaviour).
        $this->check('Variable scroll speed', $speedStd > 0.0, 1.5);

        // Direction changes or dwell suggest reading, not a single sweep.
        $this->check('Reading pattern (changes/dwell)', $directionChanges >= 1 || $dwellMs >= 300, 1.0);

        return $this->result(0.55);
    }
}
