"""Tests for the Aliro `kid` header derivation per spec \u00a77.2.1.

The spec defines:
    kid = SHA256("key-identifier" || 0x04 || IssuerKey_PubK.x || IssuerKey_PubK.y)[:8]

where "key-identifier" is the literal ASCII string.
"""

import hashlib

from cryptography.hazmat.primitives.asymmetric import ec

from aliro_harness.issuer.kid import compute_issuer_kid


def test_kid_is_8_bytes():
    key = ec.generate_private_key(ec.SECP256R1())
    kid = compute_issuer_kid(key.public_key())
    assert isinstance(kid, bytes)
    assert len(kid) == 8


def test_kid_matches_spec_formula():
    """Reference check: re-derive the kid from scratch and compare."""
    key = ec.generate_private_key(ec.SECP256R1())
    pub = key.public_key()
    numbers = pub.public_numbers()
    x_bytes = numbers.x.to_bytes(32, "big")
    y_bytes = numbers.y.to_bytes(32, "big")
    expected_input = b"key-identifier" + b"\x04" + x_bytes + y_bytes
    expected_kid = hashlib.sha256(expected_input).digest()[:8]

    assert compute_issuer_kid(pub) == expected_kid


def test_kid_is_deterministic():
    key = ec.generate_private_key(ec.SECP256R1())
    pub = key.public_key()
    assert compute_issuer_kid(pub) == compute_issuer_kid(pub)


def test_kid_differs_for_different_keys():
    key_a = ec.generate_private_key(ec.SECP256R1())
    key_b = ec.generate_private_key(ec.SECP256R1())
    assert compute_issuer_kid(key_a.public_key()) != compute_issuer_kid(key_b.public_key())
