import unittest

from scripts.lab_loop import LoopError, issue_label_names, transition, validate_owner


class LoopProtocolTests(unittest.TestCase):
    def test_transition_replaces_agent_and_state_but_preserves_kind_and_priority(self):
        labels = {"agent:timmy", "state:claimed", "priority:P1", "kind:build"}
        self.assertEqual(
            transition(labels, agent="vincent", state="ready"),
            {"agent:vincent", "state:ready", "priority:P1", "kind:build"},
        )

    def test_same_agent_transition_is_idempotent(self):
        labels = {"agent:timmy", "state:ready", "priority:P0"}
        self.assertEqual(transition(labels, agent="timmy", state="ready"), labels)

    def test_invalid_agent_fails_closed(self):
        with self.assertRaises(LoopError):
            transition(set(), agent="unknown", state="ready")

    def test_validate_owner_requires_both_labels(self):
        issue = {
            "number": 7,
            "labels": [{"name": "agent:vincent"}, {"name": "state:claimed"}],
        }
        self.assertEqual(validate_owner(issue, "vincent", "claimed"), {"agent:vincent", "state:claimed"})
        with self.assertRaises(LoopError):
            validate_owner(issue, "timmy", "claimed")
        with self.assertRaises(LoopError):
            validate_owner(issue, "vincent", "ready")

    def test_issue_label_names_handles_missing_labels(self):
        self.assertEqual(issue_label_names({}), set())


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