import json, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import verify_ref as V
d = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "vectors.json")))
k = d["test_keys"]; ok = fail = 0
for v in d["vectors"]:
    try:
        if v["format"] == "mizan-compact/3":
            pub = bytes.fromhex(k["ed25519_public_hex"] if v["alg"] == "ed25519" else k["secp256k1_public_compressed_hex"])
            e = v["expect"]
            V.verify_compact3(bytes.fromhex(v["bytes_hex"]), bytes.fromhex(v["signature_hex"]), v["alg"], pub, e["kind"], bytes.fromhex(e["subject_hex"]),
                              bytes.fromhex(e["requirement_hex"]), e["min_rung"], bytes.fromhex(e["principal_hex"]), v["now"])
        elif v["format"] == "eip712v3":
            e = v["expect"]
            V.verify_eip712v3(v["receipt"], bytes.fromhex(v["signature_hex"]), k["eip712_signer"], e["subject"], e["requirement_hex"], e["min_rung"], e["principal_hex"], v["now"])
        elif v["format"] == "mizan-compact/2":
            pub = bytes.fromhex(k["ed25519_public_hex"] if v["alg"] == "ed25519" else k["secp256k1_public_compressed_hex"])
            e = v["expect"]
            V.verify_compact2(bytes.fromhex(v["bytes_hex"]), bytes.fromhex(v["signature_hex"]), v["alg"], pub, e["kind"], bytes.fromhex(e["subject_hex"]),
                              bytes.fromhex(e["requirement_hex"]), e["min_rung"], v["now"])
        elif v["format"] == "eip712v2":
            e = v["expect"]
            V.verify_eip712v2(v["receipt"], bytes.fromhex(v["signature_hex"]), k["eip712_signer"], e["subject"], e["requirement_hex"], e["min_rung"], v["now"])
        elif v["format"] == "eip712":
            V.verify_eip712(v["receipt"], bytes.fromhex(v["signature_hex"]), k["eip712_signer"], v["expect"]["subject"], v["now"])
        else:
            pub = bytes.fromhex(k["ed25519_public_hex"] if v["alg"] == "ed25519" else k["secp256k1_public_compressed_hex"])
            V.verify_compact(bytes.fromhex(v["bytes_hex"]), bytes.fromhex(v["signature_hex"]), v["alg"], pub, v["expect"]["kind"],
                             bytes.fromhex(v["expect"]["subject_hex"]), v["now"])
        got, err = True, None
    except ValueError as e:
        got, err = False, str(e)
    if got == v["valid"]:
        ok += 1
    else:
        fail += 1; print("MISMATCH", v["id"], "expected", v["valid"], "got", got, err)
print(f"python: {ok}/{ok+fail} conform")
sys.exit(1 if fail else 0)
