import json
import unittest
from unittest.mock import MagicMock, patch

from GramAddict.core.telepathic_engine import TelepathicEngine


class TestCommentHallucination(unittest.TestCase):
    def setUp(self):
        self.engine = TelepathicEngine()
        # Mocking an XML structure where a 'Message' tab appears at the bottom (nav bar).
        # It lacks the structural markers of a comment text box.
        self.xml = """
        <hierarchy>
          <node package="com.instagram.android">
            <node content-desc="Post" bounds="[0,0][1080,1920]" />
            <node content-desc="Message" bounds="[800,2100][1000,2300]" />
          </node>
        </hierarchy>
        """

    def test_repro_vlm_tab_hallucination(self):
        """
        Verify that a navigation tab is REJECTED as a 'Comment input field'
        due to structural guards.
        """
        # Mock LLM response (picking index 1 which is the DM tab)
        mock_llm_json = json.dumps({"index": 1, "reason": "It says Message"})

        with patch("GramAddict.core.telepathic_engine.query_telepathic_llm", return_value=mock_llm_json):
            # Inspect what find_best_node considers 'viable'
            # (We cannot easily intercept internal local variables, so lets just run and see failures)
            # Provide a device mock that has a valid displayHeight
            mock_device = MagicMock()
            mock_device.get_info.return_value = {"displayHeight": 2400}
            node = self.engine.find_best_node(self.xml, "Comment input text box editfield", device=mock_device)

            # ASSERTION: The node should be None because the structural guard REJECTED the DM tab in Nav Bar zone.
            self.assertIsNone(node, f"Found {node}! Structural guard should have rejected the DM tab.")

            print("\n[V] VERIFICATION SUCCESSFUL: Structural Guard successfully rejected DM tab.")


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