import os
import sys
import unittest

# Add project root to path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))

from GramAddict.core.telepathic_engine import TelepathicEngine


class TestReproReelsTabHallucination(unittest.TestCase):
    def setUp(self):
        self.engine = TelepathicEngine()
        # Path to home feed fixture
        self.fixture_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "../fixtures/home_feed_with_ad.xml")
        )
        with open(self.fixture_path, "r", encoding="utf-8") as f:
            self.xml_content = f.read()

    def test_reels_tab_selection(self):
        """
        Verify that the engine selects the actual Reels tab (clips_tab)
        and NOT the "Add to story" badge (reel_empty_badge).
        """
        intent = "tap reels tab"

        # We need to simulate the environment where this fails.
        # Currently, 'tab' is in the filler list, so "tap reels tab" -> ["reels"]
        # "Add to story" (id: reel_empty_badge) matches "reels" (via alias "reel").
        # "Reels" (id: clips_tab) matches "reels" (via content-desc or rid).

        result = self.engine.find_best_node(self.xml_content, intent)

        self.assertIsNotNone(result, "Should have found a node")

        # In the fixture:
        # Clips tab is at [216,2235][432,2361] -> center is (324, 2298)
        # Add to story? Wait, let's find it in the XML.
        # Actually, let's search for "reel" in the XML to see candidates.

        print(f"Target selected: {result.get('semantic')} at ({result.get('x')}, {result.get('y')})")

        # The Reels tab (clips_tab) has y > 2200.
        # The "Add to story" badge is usually at the top.

        # If it selects something at the top, it's a hallucination.
        self.assertGreater(result["y"], 2000, "Should select a tab at the bottom, not an element at the top")
        self.assertIn("clips tab", result["semantic"].lower(), "Should select the clips_tab")


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