import os
import sys
import unittest

# Add parent dir to path
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from GramAddict.core.telepathic_engine import TelepathicEngine


class DummyDevice:
    class DeviceV2:
        def __init__(self):
            self.last_click = None

        def click(self, x, y):
            self.last_click = (x, y)

        def screenshot(self, path=None):
            return "fake_screenshot"

    def __init__(self):
        import unittest

        self.deviceV2 = self.DeviceV2()
        self.app_id = "com.instagram.android"
        self.args = unittest.mock.MagicMock()
        self.args.ai_telepathic_model = "qwen2.5:3b"
        self.args.ai_telepathic_url = "http://localhost:11434/api/generate"

    def _get_current_app(self):
        return "com.instagram.android"

    def get_info(self):
        return {"displayHeight": 2400, "displayWidth": 1080}

    def screenshot(self, path=None):
        return "fake_screenshot"


class TestHumanHesitation(unittest.TestCase):
    def setUp(self):
        self.telepathic = TelepathicEngine()
        self.device = DummyDevice()

    def test_discard_dialog_extraction(self):
        """
        Prove that the Telepathic Engine can correctly identify the 'Discard'
        button inside a synthetic XML dump, ensuring the 'Umentscheidung'
        abort logic works in the wild.
        """
        # Synthetic Discard Dialog XML
        synthetic_dump = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
        <hierarchy rotation="0">
            <node index="0" bounds="[0,0][1080,2400]" package="com.instagram.android">
                <node index="1" class="android.widget.TextView" text="Discard Comment?" bounds="[200,1000][800,1100]" />
                <node index="2" class="android.widget.Button" text="IGNORE" content-desc="IGNORE" bounds="[200,1200][400,1300]" />
                <node index="3" class="android.widget.Button" text="Verwerfen" content-desc="Discard or Verwerfen popup button" bounds="[600,1200][800,1300]" resource-id="com.instagram.android:id/button_discard" />
            </node>
        </hierarchy>
        """

        # Act
        result = self.telepathic.find_best_node(
            synthetic_dump,
            "Discard or Verwerfen popup button to cancel comment",
            device=self.device,
            min_confidence=0.5,
        )

        # Assert (Should hit the [600,1200][800,1300] box, which centers to (700, 1250))
        self.assertIsNotNone(result, "Telepathic engine failed to find 'Verwerfen'.")
        self.assertEqual(result["x"], 700)
        self.assertEqual(result["y"], 1250)

    def test_dm_inbox_tab_resolution(self):
        """
        Verify that teleporting specifically to the Inbox tab (DM button)
        succeeds if 'Message' describes it.
        """
        synthetic_dump = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
        <hierarchy rotation="0">
            <node index="2" text="" id="direct_tab" package="com.instagram.android" content-desc="Direct messages tab button" bounds="[432,2235][648,2361]" resource-id="com.instagram.android:id/direct_tab">
                <node content-desc=""/>
            </node>
        </hierarchy>"""

        # If ID didn't match perfectly, we fall back to description as programmed.
        # Direct simulation of UI Automator check isn't in scope for this telepathic test,
        # but we can ensure Telepathic Engine CAN find it if we rely on it.
        result = self.telepathic.find_best_node(synthetic_dump, "Direct messages tab button", device=self.device)
        self.assertIsNotNone(result, "Should find the Message tab")


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