<?php

namespace App\Services;

class BotScoreService
{
    public function calculateBotScore(array $fingerprint, array $behavior): int
    {
        $score = 0;

        if (!empty($fingerprint['webdriver'])) {
            $score += 50;
        }
        if (!empty($fingerprint['headlessRenderer'])) {
            $score += 40;
        }
        if (!empty($fingerprint['canvasBlank'])) {
            $score += 20;
        }

        if (($fingerprint['pluginCount'] ?? -1) === 0) {
            $score += 10;
        }
        $missingAPIs = (int) ($fingerprint['missingAPIs'] ?? 0);
        if ($missingAPIs > 0) {
            $score += $missingAPIs * 8;
        }
        if (
            ($fingerprint['screenWidth'] ?? 1) === 0
            || ($fingerprint['screenHeight'] ?? 1) === 0
        ) {
            $score += 15;
        }
        if (!empty($fingerprint['touchMismatch'])) {
            $score += 10;
        }

        $mouseMoveCount = (int) ($behavior['mouseMoveCount'] ?? 0);
        $mouseDistancePx = (float) ($behavior['mouseDistancePx'] ?? 0);
        $scrollCount = (int) ($behavior['scrollCount'] ?? 0);
        $timeToFirstInteractionMs = $behavior['timeToFirstInteractionMs'] ?? null;

        if ($mouseMoveCount === 0) {
            $score += 20;
        } elseif ($mouseMoveCount > 15) {
            $score -= 15;
        }
        if ($mouseMoveCount > 0 && $mouseDistancePx < 10) {
            $score += 10;
        }
        if ($scrollCount > 0) {
            $score -= 10;
        }
        if ($timeToFirstInteractionMs !== null && $timeToFirstInteractionMs < 200) {
            $score += 15;
        }
        if ($timeToFirstInteractionMs === null) {
            $score += 10;
        }

        return min(100, max(0, $score));
    }

    public function getVerdict(int $score): string
    {
        if ($score >= 61) {
            return 'bot';
        }
        if ($score >= 31) {
            return 'suspicious';
        }

        return 'clean';
    }
}
