from __future__ import annotations

import pytest

from botindex_aar.canonicalize import canonicalize, canonicalize_for_signing


def test_canonicalize_sorts_keys_deep() -> None:
    value = {
        "z": 1,
        "a": {
            "d": 4,
            "c": [
                {"b": 2, "a": 1},
                3,
            ],
        },
    }
    assert canonicalize(value) == '{"a":{"c":[{"a":1,"b":2},3],"d":4},"z":1}'


def test_canonicalize_for_signing_removes_signature_sig() -> None:
    receipt = {
        "receiptId": "r1",
        "signature": {
            "alg": "Ed25519",
            "kid": "k1",
            "canonicalization": "JCS-SORTED-UTF8-NOWS",
            "sig": "abc",
        },
    }
    assert canonicalize_for_signing(receipt) == (
        '{"receiptId":"r1","signature":{"alg":"Ed25519","canonicalization":"JCS-SORTED-UTF8-NOWS","kid":"k1"}}'
    )


def test_canonicalize_for_signing_invalid_signature() -> None:
    with pytest.raises(ValueError, match="Invalid receipt.signature"):
        canonicalize_for_signing({"signature": "bad"})
