"""Host teaching fixture. macOS, clang, radare2 and Homebrew OpenSSL 3.

Run from this directory: python3 native_check.py
Builds in a temporary folder and compares C and Python HMAC output.
"""
import ctypes
import hashlib
import hmac
import subprocess
import tempfile
from pathlib import Path

source = Path(__file__).with_name("native_signer.c")
with tempfile.TemporaryDirectory(prefix="sreverse-owned-native-") as directory:
    library = Path(directory) / "native-fixture.dylib"
    subprocess.run(["clang", "-dynamiclib", "-O0", "-g", str(source),
                    "-I/opt/homebrew/opt/openssl@3/include",
                    "-L/opt/homebrew/opt/openssl@3/lib", "-lcrypto", "-o", str(library)],
                   check=True, timeout=30)
    native = ctypes.CDLL(str(library))
    native.fixture_sign.argtypes = [ctypes.c_char_p, ctypes.c_ulong, ctypes.c_void_p]
    native.fixture_sign.restype = ctypes.c_int
    body = b'{"sku":"demo","count":7}'
    output = ctypes.create_string_buffer(32)
    assert native.fixture_sign(body, len(body), output) == 32
    expected = hmac.new(b"public-fixture-key", body, hashlib.sha256).digest()
    assert output.raw == expected
    analysis = subprocess.run(["r2", "-q", "-A", "-c", "ii;afl", str(library)],
                              capture_output=True, text=True, check=True, timeout=30)
    assert "HMAC" in analysis.stdout and "fixture_sign" in analysis.stdout
    print("PASS: native HMAC equals Python; radare2 finds HMAC import and fixture_sign")
    print(expected.hex())
