import unittest
from collections import Counter

from h8536.emulator.constants import IPRE, SCI1_SCR, SCI1_TDR, SCI_SCR_TE
from h8536.emulator.probe import ProbeReport, SCI1Snapshot, SCI1TXISummary, run_probe


def rom_with_reset(*, reset: int = 0x1000, size: int = 0x1040) -> bytearray:
    rom = bytearray([0xFF] * size)
    rom[0:2] = reset.to_bytes(2, "big")
    return rom


class EmulatorProbeSciTest(unittest.TestCase):
    def test_report_lines_include_compact_sci_state_and_txi_summary(self):
        report = ProbeReport(
            steps=12,
            pc=0xBA68,
            stopped_reason="max_steps",
            hot_pcs=Counter({0xBA68: 7}),
            tx_bytes=b"\x00\x03",
            sci_accesses=[
                "old write SCR=00",
                "H'BA60 read SSR=00",
                "H'BA64 write SCR=A0",
                "H'BA68 write TDR=03",
            ],
            sci1=SCI1Snapshot(
                smr=0x00,
                brr=0x07,
                scr=0xA0,
                ssr=0x80,
                tdr=0x03,
                rdr=0x00,
                tx_ready_delay=1,
            ),
            sci1_txi=SCI1TXISummary(
                tie=True,
                te=True,
                tdre=True,
                vector_target=0xBA68,
                priority=6,
                interrupt_mask=2,
                interrupt_depth=0,
            ),
        )

        lines = report.lines()

        self.assertIn("sci1=SMR=00 BRR=07 SCR=A0 SSR=80 TDR=03 RDR=00 tx_ready_delay=1", lines)
        self.assertIn(
            "sci1_txi=TIE=1 TE=1 TDRE=1 vector=H'BA68 priority=6 mask=2 depth=0 pending=1 serviceable=1",
            lines,
        )
        self.assertIn("recent_sci:", lines)
        self.assertIn("  H'BA60 read SSR=00", lines)
        self.assertIn("  H'BA68 write TDR=03", lines)

    def test_report_lines_bound_recent_sci_accesses(self):
        report = ProbeReport(
            steps=1,
            pc=0x1000,
            stopped_reason="max_steps",
            sci_accesses=[f"H'{idx:04X} read SSR={idx:02X}" for idx in range(20)],
        )

        lines = report.lines()

        self.assertNotIn("  H'0000 read SSR=00", lines)
        self.assertIn("  H'0004 read SSR=04", lines)
        self.assertIn("  H'0013 read SSR=13", lines)

    def test_run_probe_tracks_sci_register_accesses_and_final_txi_state(self):
        rom = rom_with_reset()
        rom[0x0084:0x0086] = (0x1010).to_bytes(2, "big")
        rom[0x1000:0x1003] = b"\x5F\xFE\x80"  # MOV:I.W #H'FE80, R7
        rom[0x1003:0x1008] = bytes([0x15, (IPRE >> 8) & 0xFF, IPRE & 0xFF, 0x06, 0x50])
        rom[0x1008:0x100D] = bytes([0x15, (SCI1_SCR >> 8) & 0xFF, SCI1_SCR & 0xFF, 0x06, 0xA0])
        rom[0x100D] = 0x00
        rom[0x1010:0x1015] = bytes([0x15, (SCI1_SCR >> 8) & 0xFF, SCI1_SCR & 0xFF, 0x06, SCI_SCR_TE])
        rom[0x1015:0x101A] = bytes([0x15, (SCI1_TDR >> 8) & 0xFF, SCI1_TDR & 0xFF, 0x06, 0x42])
        rom[0x101A] = 0x0A

        report = run_probe(
            bytes(rom),
            max_steps=8,
            interval_steps=512,
            stop_on_tx=False,
            p9_log_limit=8,
            sci_log_limit=8,
            watch_pcs=(),
        )

        self.assertEqual(report.tx_bytes, b"\x42")
        self.assertIsNotNone(report.sci1)
        self.assertIsNotNone(report.sci1_txi)
        self.assertTrue(any("write SCR=A0" in line for line in report.sci_accesses))
        self.assertTrue(any("write SCR=20" in line for line in report.sci_accesses))
        self.assertTrue(any("write TDR=42" in line for line in report.sci_accesses))
        self.assertTrue(any(line.startswith("sci1=SMR=00") for line in report.lines()))


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