import io
import json
import tempfile
import unittest
from pathlib import Path

from h8536.serial_scenario import DEFAULT_ACK_FRAME, DEFAULT_ACK_TARGET, main


class SerialScenarioTest(unittest.TestCase):
    def test_dry_run_summarizes_ack_aware_table_sweep(self):
        scenario = {
            "name": "unit-sweep",
            "steps": [
                {
                    "action": "table_sweep",
                    "start": "0x000",
                    "count": "0x002",
                    "gap": 0.75,
                    "ack_on": {
                        "frames": ["07 80 40 20 90 2D"],
                        "ack_frame": "05 00 40 00 00 1F",
                        "max_acks": 8,
                        "max_target_hits": 32,
                    },
                }
            ],
        }
        with tempfile.TemporaryDirectory() as tmpdir:
            path = Path(tmpdir) / "scenario.json"
            path.write_text(json.dumps(scenario), encoding="utf-8")
            stdout = io.StringIO()

            exit_code = main([str(path), "--dry-run"], stdout=stdout)

        output = stdout.getvalue()
        self.assertEqual(exit_code, 0)
        self.assertIn("scenario=unit-sweep", output)
        self.assertIn("selectors=2 first=0x000 last=0x001", output)
        self.assertIn("ack_target=07 80 40 20 90 2D", output)
        self.assertIn("ack_frame=05 00 40 00 00 1F", output)
        self.assertIn("max_acks=8 max_target_hits=32", output)

    def test_default_ack_frames_match_current_rom_probe_candidate(self):
        self.assertEqual(DEFAULT_ACK_TARGET, bytes.fromhex("07804020902D"))
        self.assertEqual(DEFAULT_ACK_FRAME, bytes.fromhex("05004000001F"))


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