"""Tests for the Access Document APDU sequence builder."""

import pytest

from aliro_harness.personalizer.access_document import (
    ACCESS_DOC_MAX_LEN,
    APDU_CHUNK_MAX,
    CLA_PROPRIETARY,
    INS_FINALIZE_ACCESS_DOC,
    INS_WRITE_ACCESS_DOC,
    access_document_apdus,
)


def test_small_ad_emits_one_write_then_finalize():
    ad = bytes(range(50))
    apdus = access_document_apdus(ad)
    assert len(apdus) == 2, "small AD => 1 WRITE + 1 FINALIZE"

    write = apdus[0]
    assert write[0] == CLA_PROPRIETARY
    assert write[1] == INS_WRITE_ACCESS_DOC
    assert write[2] == 0 and write[3] == 0, "first chunk at offset 0"
    assert write[4] == len(ad)
    assert write[5 : 5 + len(ad)] == ad

    finalize = apdus[1]
    assert finalize == bytes([CLA_PROPRIETARY, INS_FINALIZE_ACCESS_DOC, 0x00, len(ad)])


def test_ad_over_chunk_size_splits_into_multiple_writes():
    ad = bytes(i & 0xFF for i in range(600))
    apdus = access_document_apdus(ad, chunk_size=255)
    # 600 bytes @ 255/chunk = 3 writes (255 + 255 + 90), + 1 finalize
    assert len(apdus) == 4

    # Check offsets and chunk boundaries.
    assert apdus[0][2:4] == bytes([0, 0])
    assert apdus[0][4] == 255
    assert apdus[1][2:4] == bytes([255 >> 8, 255 & 0xFF])
    assert apdus[1][4] == 255
    assert apdus[2][2:4] == bytes([510 >> 8, 510 & 0xFF])
    assert apdus[2][4] == 90
    assert apdus[3][0:2] == bytes([CLA_PROPRIETARY, INS_FINALIZE_ACCESS_DOC])
    assert apdus[3][2:4] == bytes([600 >> 8, 600 & 0xFF])


def test_concatenated_write_payloads_reconstruct_the_original_ad():
    ad = bytes(i & 0xFF for i in range(777))
    apdus = access_document_apdus(ad)
    reconstructed = b"".join(a[5:] for a in apdus if a[1] == INS_WRITE_ACCESS_DOC)
    assert reconstructed == ad


def test_ad_exactly_at_budget_is_accepted():
    ad = bytes(ACCESS_DOC_MAX_LEN)
    apdus = access_document_apdus(ad)
    assert apdus[-1][2] == (ACCESS_DOC_MAX_LEN >> 8)
    assert apdus[-1][3] == (ACCESS_DOC_MAX_LEN & 0xFF)


def test_ad_over_budget_is_rejected():
    ad = bytes(ACCESS_DOC_MAX_LEN + 1)
    with pytest.raises(ValueError, match="exceeds"):
        access_document_apdus(ad)


def test_chunk_size_out_of_range_is_rejected():
    with pytest.raises(ValueError, match="chunk_size"):
        access_document_apdus(b"x", chunk_size=0)
    with pytest.raises(ValueError, match="chunk_size"):
        access_document_apdus(b"x", chunk_size=APDU_CHUNK_MAX + 1)
