<?php
declare(strict_types=1);

use SafeTun\Backend\Storage\NonceStore;
use SafeTun\Backend\Storage\RateLimiter;

require dirname(__DIR__) . '/src/autoload.php';

$serverArguments = $_SERVER['argv'] ?? [];
if (!is_array($serverArguments) || !array_is_list($serverArguments)) {
    echo 'E';
    exit(2);
}
/** @var list<string> $arguments */
$arguments = array_values(array_filter($serverArguments, 'is_string'));
if (count($arguments) !== count($serverArguments)) {
    echo 'E';
    exit(2);
}

try {
    if (($arguments[1] ?? '') === 'nonce' && count($arguments) === 7) {
        (new NonceStore($arguments[2]))->consume($arguments[3], $arguments[4], $arguments[5], (int) $arguments[6]);
        echo '1';
        exit(0);
    }
    if (($arguments[1] ?? '') === 'rate' && count($arguments) === 8) {
        $allowed = (new RateLimiter($arguments[2]))->allow(
            $arguments[3], (int) $arguments[4], (int) $arguments[5], (int) $arguments[6],
        );
        echo $allowed ? '1' : '0';
        exit(0);
    }
    echo 'E';
    exit(2);
} catch (InvalidArgumentException) {
    echo '0';
    exit(0);
} catch (Throwable) {
    echo 'E';
    exit(1);
}
