"""
E2E: Foreign App Workflow
=========================
Tests the FULL production pipeline when the device has navigated
to a foreign app (Chrome, Settings, etc.) instead of Instagram.

Mock: ONLY the device (XML dumps).
Real: Cognitive stack, PluginRegistry, SessionState, Config.
"""

CHROME_XML = """<?xml version="1.0" encoding="utf-8"?>
<hierarchy rotation="0">
    <node class="android.widget.FrameLayout" package="com.android.chrome"
          bounds="[0,0][1080,2400]">
        <node text="https://www.example.com"
              class="android.widget.EditText"
              resource-id="com.android.chrome:id/url_bar" />
        <node text="Example Domain"
              class="android.widget.TextView" />
    </node>
</hierarchy>
"""

NORMAL_POST_XML = """<?xml version="1.0" encoding="utf-8"?>
<hierarchy rotation="0">
    <node class="android.widget.FrameLayout" package="com.instagram.android"
          bounds="[0,0][1080,2400]">
        <node resource-id="com.instagram.android:id/row_feed_button_like"
              class="android.widget.ImageView" clickable="true"
              content-desc="Like" bounds="[30,1360][120,1450]" />
    </node>
</hierarchy>
"""


def test_foreign_app_terminates_chain(make_real_device_with_xml, e2e_workflow_ctx):
    """
    When Chrome is in the foreground, the full pipeline must:
    detect OBSTACLE_FOREIGN_APP → press BACK → skip all interactions.
    """

    device = make_real_device_with_xml([CHROME_XML, NORMAL_POST_XML])
    results, ctx = e2e_workflow_ctx(device, context_xml=CHROME_XML)

    guard_fired = any(r.executed and r.should_skip for r in results)
    assert guard_fired, "obstacle_guard did not fire on foreign app — " "interaction plugins would run against Chrome!"

    total_interactions = sum(r.interactions for r in results)
    assert total_interactions == 0, f"{total_interactions} interaction(s) performed on Chrome!"

    assert "back" in device.pressed_keys, "obstacle_guard did not press BACK to return to Instagram!"
