<?php
if (!defined('WD')) { define('WD', __DIR__ . '/../../'); }
require_once WD . '/vendor/autoload.php';
require_once WD . '/classes/webauthn.php';

use classes\webauthn;

// A minimal EC P-256 public key in PEM format for testing.
// This is not a real WebAuthn key; it's just for conversion testing.
// Generated example (for test only). Replace with a small static PEM that OpenSSL can parse.
$pem = "-----BEGIN PUBLIC KEY-----\n"
    . "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
    . "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\n"
    . "-----END PUBLIC KEY-----\n";

// Base64URL-encode the PEM as stored by the API
$b64urlPem = rtrim(strtr(base64_encode($pem), '+/', '-_'), '=');

$wa = new webauthn();
$refl = new ReflectionClass($wa);
$ensure = $refl->getMethod('ensureCosePublicKey');
$ensure->setAccessible(true);

if (!function_exists('openssl_pkey_get_public')) {
    echo "SKIP: openssl extension not available on host PHP CLI.\n";
    exit(0);
}

try {
    $cose = $ensure->invoke($wa, base64_decode(strtr($b64urlPem, '-_', '+/')), 'ES256');
    // Basic sanity checks: COSE map tends to start with 0xA5 (5 pairs) for our 5 keys
    $first = ord($cose[0]);
    echo "COSE starts with: 0x" . dechex($first) . "\n";
    echo "Length: " . strlen($cose) . "\n";
    echo ($first >= 0xA0 && $first <= 0xBF) ? "✔ Looks like a CBOR map\n" : "✘ Unexpected CBOR prefix\n";
} catch (Exception $e) {
    echo "Conversion failed: " . $e->getMessage() . "\n";
}
