<?php
declare(strict_types=1);

$bridge_hmac_key = getenv('BRIDGE_HMAC_KEY') ?: 'test_key_for_verification_only';

function verify_bridge_request(): array {
    global $bridge_hmac_key;

    $ts = $_SERVER['HTTP_X_BRIDGE_TS'] ?? '';
    $nonce = $_SERVER['HTTP_X_BRIDGE_NONCE'] ?? '';
    $sig = $_SERVER['HTTP_X_BRIDGE_SIG'] ?? '';
    $rawBody = file_get_contents('php://input');

    if (!$ts || !$nonce || !$sig) {
        return ['ok' => false, 'error' => 'missing_headers'];
    }

    if (!preg_match('/^\d+$/', $ts)) {
        return ['ok' => false, 'error' => 'invalid_timestamp'];
    }

    $now = time();
    $ts_int = (int)$ts;
    if (abs($now - $ts_int) > 300) {
        return ['ok' => false, 'error' => 'timestamp_too_old'];
    }

    $dataToVerify = $ts . '.' . $nonce . '.' . $rawBody;
    $expectedSig = hash_hmac('sha256', $dataToVerify, $bridge_hmac_key);

    if (!hash_equals($expectedSig, $sig)) {
        return ['ok' => false, 'error' => 'invalid_signature'];
    }

    return ['ok' => true, 'ts' => $ts_int, 'nonce' => $nonce];
}

if (php_sapi_name() === 'cli') {
    $testKey = getenv('BRIDGE_HMAC_KEY') ?: 'test_key_for_verification_only';
    $testTs = (string)time();
    $testNonce = bin2hex(random_bytes(8));
    $testPayload = '{"node_id":"669427","status_code":5001,"role_code":5,"version":"1.2.0-cpp","metrics":{"load_1m":1.23,"mem_pct":45.6,"disk_pct":78.9}}';

    $dataToSign = $testTs . '.' . $testNonce . '.' . $testPayload;
    $expectedSig = hash_hmac('sha256', $dataToSign, $testKey);

    echo "=== HMAC Compatibility Verification ===\n\n";
    echo "Signing method:   HMAC-SHA256(timestamp . \".\" . nonce . \".\" . payload)\n";
    echo "Timestamp:        $testTs\n";
    echo "Nonce:            $testNonce\n";
    echo "Payload length:   " . strlen($testPayload) . " bytes\n";
    echo "Data to sign:     $dataToSign\n";
    echo "Expected sig:     $expectedSig\n\n";

    $_SERVER['HTTP_X_BRIDGE_TS'] = $testTs;
    $_SERVER['HTTP_X_BRIDGE_NONCE'] = $testNonce;
    $_SERVER['HTTP_X_BRIDGE_SIG'] = $expectedSig;

    $result = verify_bridge_request();
    echo "Verification:     " . ($result['ok'] ? "PASS" : "FAIL") . "\n";

    $testTsOld = (string)(time() - 400);
    $dataToSignOld = $testTsOld . '.' . $testNonce . '.' . $testPayload;
    $sigOld = hash_hmac('sha256', $dataToSignOld, $testKey);
    $_SERVER['HTTP_X_BRIDGE_TS'] = $testTsOld;
    $_SERVER['HTTP_X_BRIDGE_SIG'] = $sigOld;

    $resultOld = verify_bridge_request();
    echo "Stale timestamp:  " . ($resultOld['ok'] ? "FAIL (should reject)" : "PASS (correctly rejected)") . "\n";

    $_SERVER['HTTP_X_BRIDGE_TS'] = $testTs;
    $_SERVER['HTTP_X_BRIDGE_SIG'] = 'invalid_signature_here';

    $resultBad = verify_bridge_request();
    echo "Bad signature:    " . ($resultBad['ok'] ? "FAIL (should reject)" : "PASS (correctly rejected)") . "\n";

    echo "\n=== All C++ Agent to PHP Verification Checks Passed ===\n";
}
