import json
import tempfile
import unittest
from pathlib import Path

from h8536.board_profile import analyze_board_profile
from h8536.model import Instruction
from h8536.pseudocode import PseudocodeOptions, generate_pseudocode
from h8536.render import format_listing, write_json
from h8536.rom import Rom
from h8536.sci_protocol import analyze_sci_protocol


class BoardSciIntegrationTest(unittest.TestCase):
    def test_listing_json_and_pseudocode_include_rs232_path_comments(self):
        instructions = {
            0x1000: Instruction(
                0x1000,
                b"\x15\xFE\xDA\x06\x3C",
                "MOV:G.B",
                "#H'3C, @SCI1_SCR",
                references=[0xFEDA],
                comment="SCI1_SCR = H'3C",
            ),
            0x1005: Instruction(
                0x1005,
                b"\x15\xFE\xDB\x90",
                "MOV:G.B",
                "R0, @SCI1_TDR",
                references=[0xFEDB],
            ),
            0x1009: Instruction(
                0x1009,
                b"\x15\xFE\xDD\x80",
                "MOV:G.B",
                "@SCI1_RDR, R0",
                references=[0xFEDD],
            ),
        }
        sci_protocol = analyze_sci_protocol(instructions)
        board_profile = analyze_board_profile(instructions)

        listing = format_listing(
            Path("rom.bin"),
            Rom(b"\xFF" * 0x20),
            instructions,
            {},
            {},
            "min",
            traced=False,
            sci_protocol=sci_protocol,
            board_profile=board_profile,
        )

        self.assertIn("; Board Profile", listing)
        self.assertIn("H8 pin 66 P95/TXD", listing)
        self.assertIn("write RS232/SCI byte to SCI1 TDR", listing)
        self.assertIn("MAX202 pin 12 -> H8 pin 67 P96/RXD", listing)

        with tempfile.TemporaryDirectory() as tmp:
            path = Path(tmp) / "out.json"
            write_json(path, instructions, {}, {}, sci_protocol=sci_protocol, board_profile=board_profile)
            payload = json.loads(path.read_text(encoding="utf-8"))

        self.assertEqual(payload["board_profile"]["board"], "sony_rcp_tx7")
        self.assertEqual(payload["board_profile"]["traces"][0]["max202_pin"], 11)
        tdr_instruction = next(item for item in payload["instructions"] if item["address"] == 0x1005)
        self.assertEqual(tdr_instruction["sci_protocol"][0]["action"], "write_tdr")
        self.assertIn("board_profile", tdr_instruction)

        pseudocode = generate_pseudocode(
            payload,
            options=PseudocodeOptions(include_addresses=False, include_asm=False, structured=False),
        )
        self.assertIn("write RS232/SCI byte to SCI1 TDR", pseudocode)
        self.assertIn("H8 pin 66 P95/TXD -> MAX202 pin 11", pseudocode)


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