<?php

declare(strict_types=1);

/**
 * Detection-engine simulator (CLI).
 *
 * Runs the real DetectionEngine (config-default module set, no database) over a
 * built-in "human" and "bot" sample, printing the score, classification and the
 * per-module breakdown. Useful for tuning weights and for a quick smoke test of
 * the scoring pipeline without standing up MySQL.
 *
 * Usage: php bin/simulate.php [human|bot|both]
 */

use BotGuard\Core\Config;
use BotGuard\Services\Detection\EngineFactory;
use BotGuard\Services\Detection\SignalBag;

$basePath = dirname(__DIR__);
require $basePath . '/vendor/autoload.php';
Config::boot($basePath);

/** @return array{0:array<string,mixed>,1:array<string,mixed>} */
function humanSample(): array
{
    return [
        [
            'ip'         => '203.0.113.10',
            'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
            'referer'    => 'https://www.google.com/search?q=example',
            'headers'    => [
                'accept' => 'text/html,application/xhtml+xml,*/*;q=0.8', 'accept-language' => 'en-US,en;q=0.9',
                'accept-encoding' => 'gzip, deflate, br', 'sec-ch-ua' => '"Chromium";v="126"',
                'sec-fetch-mode' => 'navigate', 'connection' => 'keep-alive',
            ],
        ],
        [
            'fingerprint' => ['screen_width' => 1920, 'screen_height' => 1080, 'timezone' => 'America/New_York',
                'languages' => ['en-US', 'en'], 'canvas_hash' => 'abc123', 'audio_hash' => 'aud9',
                'webgl_vendor' => 'Google Inc. (NVIDIA)', 'webgl_renderer' => 'ANGLE (NVIDIA RTX 3060)',
                'hardware_concurrency' => 8, 'device_memory' => 8, 'color_depth' => 24, 'touch_support' => false,
                'plugins' => ['PDF Viewer'], 'fonts' => ['Arial', 'Calibri', 'Georgia', 'Verdana'], 'hash' => 'fp-human'],
            'javascript' => ['enabled' => true, 'es6' => true, 'async' => true, 'promise' => true, 'event_loop' => true, 'webdriver' => false],
            'cookies'    => ['enabled' => true, 'persisted' => true, 'local_storage' => true, 'session_storage' => true],
            'timing'     => ['time_on_page_ms' => 7400, 'time_to_interact_ms' => 1200, 'time_to_submit_ms' => 5200],
            'honeypot'   => ['contact_email' => '', 'website' => '', 'render_delay_ms' => 6100],
            'mouse'      => ['move_count' => 180, 'speed_stddev' => 0.42, 'straightness' => 0.71, 'avg_curvature' => 0.15, 'click_count' => 3, 'click_interval_stddev' => 220.0],
            'keyboard'   => ['keydown_count' => 0],
            'scroll'     => ['event_count' => 12, 'total_distance' => 2300, 'speed_stddev' => 0.3, 'direction_changes' => 3, 'dwell_ms' => 900],
            'links'      => ['hover_count' => 4, 'avg_hover_ms' => 320.0, 'instant_clicks' => 0, 'double_clicks' => 0, 'touch_events' => 0],
            'captcha'    => ['provider' => 'puzzle', 'verified' => true, 'solve_time_ms' => 2600, 'retries' => 0],
            'rate'       => ['per_second' => 1, 'per_minute' => 3, 'per_hour' => 12],
            'session'    => ['duration_ms' => 7400, 'request_count' => 2, 'repeat_visitor' => false, 'integrity_ok' => true, 'navigation_count' => 1],
        ],
    ];
}

/** @return array{0:array<string,mixed>,1:array<string,mixed>} */
function botSample(): array
{
    return [
        [
            'ip'         => '198.51.100.7',
            'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/126.0.0.0 Safari/537.36',
            'referer'    => '',
            'headers'    => ['accept' => '*/*', 'connection' => 'close'],
        ],
        [
            'fingerprint' => ['screen_width' => 800, 'screen_height' => 600, 'timezone' => '', 'languages' => [],
                'canvas_hash' => '', 'audio_hash' => '', 'webgl_vendor' => 'Google Inc. (Google)',
                'webgl_renderer' => 'ANGLE (Google, SwiftShader)', 'hardware_concurrency' => 1, 'device_memory' => 0,
                'color_depth' => 24, 'touch_support' => false, 'plugins' => [], 'fonts' => []],
            'javascript' => ['enabled' => true, 'es6' => true, 'async' => true, 'promise' => true, 'event_loop' => true, 'webdriver' => true],
            'cookies'    => ['enabled' => false, 'persisted' => false, 'local_storage' => false, 'session_storage' => false],
            'timing'     => ['time_on_page_ms' => 120, 'time_to_interact_ms' => 20, 'time_to_submit_ms' => 90],
            'honeypot'   => ['contact_email' => 'x@bot.test', 'website' => 'http://bot.test', 'render_delay_ms' => 60],
            'mouse'      => [],
            'keyboard'   => ['keydown_count' => 0],
            'scroll'     => [],
            'links'      => ['hover_count' => 0, 'avg_hover_ms' => 0.0, 'instant_clicks' => 5, 'double_clicks' => 4, 'touch_events' => 0],
            'captcha'    => ['provider' => 'puzzle', 'verified' => false, 'solve_time_ms' => 40, 'retries' => 6],
            'rate'       => ['per_second' => 20, 'per_minute' => 300, 'per_hour' => 5000],
            'session'    => ['duration_ms' => 120, 'request_count' => 40, 'repeat_visitor' => false, 'integrity_ok' => false, 'navigation_count' => 0],
        ],
    ];
}

function render(string $label, array $sample): void
{
    $engine = (new EngineFactory(null))->make();
    $outcome = $engine->evaluate(SignalBag::fromArrays($sample[0], $sample[1]));

    $colors = ['human' => "\033[32m", 'suspicious' => "\033[33m", 'bot' => "\033[31m"];
    $c = $colors[$outcome->classification] ?? '';
    $reset = "\033[0m";

    echo "\n=== {$label} ===\n";
    echo "Score: {$outcome->score}/100   Class: {$c}" . strtoupper($outcome->classification) . "{$reset}   Action: {$outcome->action}\n";
    printf("%-16s %7s %7s  %s\n", 'MODULE', 'HUMAN%', 'WEIGHT', 'FAILED CHECKS');
    echo str_repeat('-', 78) . "\n";
    foreach ($outcome->results as $r) {
        $w = $outcome->weights[$r->key] ?? 0;
        printf("%-16s %6d%% %7s  %s\n", $r->key, (int) round($r->score * 100), $w, implode(', ', $r->failed) ?: '—');
    }
}

$which = $argv[1] ?? 'both';
if ($which === 'human' || $which === 'both') {
    render('HUMAN sample', humanSample());
}
if ($which === 'bot' || $which === 'both') {
    render('BOT sample', botSample());
}
echo "\n";
