import io
import unittest

from h8536.connect_ok_advance_sweep import build_cases, main, _matches_target


class ConnectOkAdvanceSweepTest(unittest.TestCase):
    def test_core_suite_starts_with_ack_then_refresh(self):
        cases = build_cases("core")

        self.assertEqual([case.name for case in cases], ["ack-0040", "refresh-ok"])
        self.assertEqual(cases[0].frame.hex().upper(), "05004000001F")
        self.assertEqual(cases[1].frame.hex().upper(), "0400008000DE")

    def test_latch_suite_includes_special_clear_candidates(self):
        names = [case.name for case in build_cases("latch")]

        self.assertIn("ack-0096", names)
        self.assertIn("ack-00f8", names)

    def test_dry_run_defaults_to_reactive_active_report_window(self):
        stdout = io.StringIO()

        exit_code = main(["--dry-run", "--suite", "core", "--limit", "1"], stdout=stdout)

        self.assertEqual(exit_code, 0)
        output = stdout.getvalue()
        self.assertIn("device=COM5 38400 8E1", output)
        self.assertIn("target_mode=active", output)
        self.assertIn("baseline[1]=04 00 00 80 00 DE checksum_ok=1", output)
        self.assertIn("case[1]=ack-0040 frame=05 00 40 00 00 1F checksum_ok=1", output)

    def test_custom_candidate_accepts_five_bytes_and_computes_checksum(self):
        stdout = io.StringIO()

        exit_code = main(["--dry-run", "--candidate", "probe=05 00 6D 00 00"], stdout=stdout)

        self.assertEqual(exit_code, 0)
        self.assertIn("case[1]=probe frame=05 00 6D 00 00 32 checksum_ok=1", stdout.getvalue())

    def test_active_target_ignores_heartbeat_but_accepts_report(self):
        self.assertFalse(_matches_target(bytes.fromhex("0000000080DA"), "active"))
        self.assertTrue(_matches_target(bytes.fromhex("02000200005A"), "active"))
        self.assertTrue(_matches_target(bytes.fromhex("07804040A07D"), "active"))

    def test_connect_ok_target_requires_known_ok_response(self):
        self.assertTrue(_matches_target(bytes.fromhex("02000200005A"), "connect-ok"))
        self.assertFalse(_matches_target(bytes.fromhex("010012000049"), "connect-ok"))


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