<?php
declare(strict_types=1);
namespace App\Security;
final class FormBotGuard
{
    public function __construct(private readonly string $secret='',private readonly int $minimumAgeMs=800){}
    /** @return array{started:string,signature:string} */
    public function issue(?int $nowMs=null):array{$nowMs??=(int)floor(microtime(true)*1000);$started=(string)$nowMs;return ['started'=>$started,'signature'=>$this->sign($started)];}
    /** @param array<string,mixed> $input @return array{honeypot:bool,too_fast:bool,valid_signature:bool,age_ms:int} */
    public function inspect(array $input,?int $nowMs=null):array
    {
        $nowMs??=(int)floor(microtime(true)*1000);$started=(string)($input['_qb_started']??'');$sig=(string)($input['_qb_sig']??'');$valid=$started!==''&&ctype_digit($started)&&hash_equals($this->sign($started),$sig);$age=$valid?max(0,$nowMs-(int)$started):0;
        return ['honeypot'=>trim((string)($input['_qb_hp']??''))!=='','too_fast'=>$valid&&$age<$this->minimumAgeMs,'valid_signature'=>$valid,'age_ms'=>$age];
    }
    public static function sessionGuard():self
    {
        if(session_status()!==PHP_SESSION_ACTIVE)@session_start();
        if(empty($_SESSION['quaeriva_form_guard_secret']))$_SESSION['quaeriva_form_guard_secret']=bin2hex(random_bytes(32));
        return new self((string)$_SESSION['quaeriva_form_guard_secret']);
    }
    private function sign(string $started):string{return hash_hmac('sha256',$started,$this->secret!==''?$this->secret:'quaeriva-form-guard');}
}
