import unittest

from h8536.decoder import H8536Decoder
from h8536.rom import Rom


def decode(data: list[int]):
    return H8536Decoder(Rom(bytes(data), base=0)).decode(0)


def mov_b_immediate_to_abs16(address: int, value: int):
    return decode([0x15, (address >> 8) & 0xFF, address & 0xFF, 0x06, value])


def bit_op_abs16(address: int, op: int):
    return decode([0x15, (address >> 8) & 0xFF, address & 0xFF, op])


class InterruptAnnotationTest(unittest.TestCase):
    def test_ipra_write_decodes_irq_priority_levels(self):
        instruction = mov_b_immediate_to_abs16(0xFF00, 0x75)

        self.assertEqual(instruction.text, "MOV:G.B #H'75, @IPRA")
        self.assertEqual(instruction.comment, "IPRA = H'75 (irq0 priority=7; irq1 priority=5)")

    def test_iprf_write_decodes_ad_priority_and_reserved_bits(self):
        instruction = mov_b_immediate_to_abs16(0xFF05, 0xF8)

        self.assertEqual(instruction.text, "MOV:G.B #H'F8, @IPRF")
        self.assertEqual(instruction.comment, "IPRF = H'F8 (A/D priority=7; reserved bits 7, 3 should be 0)")

    def test_dtee_write_decodes_dtc_routing_by_interrupt_source(self):
        instruction = mov_b_immediate_to_abs16(0xFF0C, 0x24)

        self.assertEqual(instruction.text, "MOV:G.B #H'24, @DTEE")
        self.assertEqual(
            instruction.comment,
            "DTEE = H'24 (SCI1 TXI CPU interrupt; SCI1 RXI DTC enabled; "
            "SCI2 TXI DTC enabled; SCI2 RXI CPU interrupt)",
        )

    def test_dtea_bit_set_names_dtc_enable_source(self):
        instruction = bit_op_abs16(0xFF08, 0xC4)

        self.assertEqual(instruction.text, "BSET.B #4, @DTEA")
        self.assertEqual(instruction.comment, "set irq0 DTC enable (bit 4) of DTEA")


if __name__ == "__main__":
    unittest.main()
