import unittest

from h8536.bench_connect_lcd import frame_checksum_ok
from h8536.serial_table_dump import build_read_frame, decode_table_read_response, encode_selector


class SerialTableDumpTest(unittest.TestCase):
    def test_encode_selector_matches_rom_loc_622b_ranges(self):
        self.assertEqual((encode_selector(0x000).frame_hi, encode_selector(0x000).frame_lo), (0x00, 0x00))
        self.assertEqual((encode_selector(0x07F).frame_hi, encode_selector(0x07F).frame_lo), (0x00, 0x7F))
        self.assertEqual((encode_selector(0x080).frame_hi, encode_selector(0x080).frame_lo), (0x01, 0x00))
        self.assertEqual((encode_selector(0x17F).frame_hi, encode_selector(0x17F).frame_lo), (0x01, 0xFF))
        self.assertEqual((encode_selector(0x180).frame_hi, encode_selector(0x180).frame_lo), (0x02, 0x00))
        self.assertEqual((encode_selector(0x1FF).frame_hi, encode_selector(0x1FF).frame_lo), (0x02, 0x7F))

    def test_build_read_frame_uses_command_1_and_checksum(self):
        frame = build_read_frame(0x180)

        self.assertEqual(frame[:5], bytes.fromhex("01 02 00 00 00"))
        self.assertTrue(frame_checksum_ok(frame))

    def test_decode_table_read_response_extracts_value_candidate(self):
        frame = bytes.fromhex("04 00 12 80 80 4C")

        self.assertEqual(decode_table_read_response(frame), (0x12, 0x8080))

    def test_decode_table_read_response_ignores_non_readback(self):
        self.assertIsNone(decode_table_read_response(bytes.fromhex("00 00 00 00 80 DA")))


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