from GramAddict.core.perception.action_memory import ActionMemory
from GramAddict.core.perception.screen_identity import ScreenIdentity, ScreenType


def test_screen_identity_detects_other_profile_with_missing_header_container():
    """
    RED: ScreenIdentity used to misclassify OTHER_PROFILE as UNKNOWN or POST_DETAIL
    if `profile_header_container` was missing, even though `row_profile_header_imageview`
    was present.
    GREEN: We added row_profile_header_imageview and profile_tabs_container.
    """
    identity = ScreenIdentity(bot_username="my_bot")

    # Simulate a profile screen that is missing the main container but has the imageview
    xml_dump = """<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
    <hierarchy>
      <node package="com.instagram.android" resource-id="com.instagram.android:id/row_profile_header_imageview" bounds="[0,0][100,100]" clickable="true"/>
      <node package="com.instagram.android" resource-id="com.instagram.android:id/profile_tabs_container" bounds="[0,200][1080,300]"/>
      <node package="com.instagram.android" resource-id="com.instagram.android:id/action_bar_title" text="justkay"/>
    </hierarchy>
    """

    result = identity.identify(xml_dump)
    assert result["screen_type"] == ScreenType.OTHER_PROFILE


def test_action_memory_verifies_profile_navigation_in_o1_without_vlm(monkeypatch):
    """
    RED: ActionMemory.verify_success used to fallback to VLM because navigating to a profile
    caused a huge delta, but there was no explicit fast-path for 'profile', causing it
    to hit `confidence < 0.95` and invoke `evaluator._query_vlm`.
    GREEN: It now structurally verifies `profile_header_container` instantly.
    """
    memory = ActionMemory()

    class DummyDevice:
        def get_screenshot_b64(self):
            raise Exception("VLM SHOULD NOT BE CALLED!")

    device = DummyDevice()

    intent = "tap post username"
    pre_xml = "<hierarchy><node/></hierarchy>"
    # Post XML contains profile_header_container!
    post_xml = "<hierarchy><node resource-id='com.instagram.android:id/profile_header_container'/></hierarchy>"

    # If the fast-path works, it will return True instantly and NOT call get_screenshot_b64
    success = memory.verify_success(
        intent=intent,
        pre_click_xml=pre_xml,
        post_click_xml=post_xml,
        device=device,
        confidence=0.0,  # low confidence triggers VLM fallback if fast-path is missing
    )

    assert success is True
