"""
E2E: Feed Loop Foreign App Escape
====================================
Validates that the feed loop detects a foreign app takeover
(e.g. Play Store opened) and immediately aborts with CONTEXT_LOST.
Parity with story loop guard.
"""

import datetime

from tests.e2e.conftest import E2EDeviceStub, load_fixture_xml


def test_feed_loop_escapes_foreign_app(e2e_configs, e2e_cognitive_stack_factory):
    """
    Simulates: Feed → Play Store.
    The loop must detect com.android.vending and abort immediately.
    """
    from GramAddict.core.bot_flow import _run_zero_latency_feed_loop

    feed_xml = load_fixture_xml("home_feed_with_ad.xml")
    play_store_xml = load_fixture_xml("play_store_from_story_link.xml")

    # Feed -> Play Store
    device = E2EDeviceStub([feed_xml, play_store_xml])

    cognitive_stack = e2e_cognitive_stack_factory(device)
    cognitive_stack["dopamine"].session_limit_seconds = 999

    session_state = type(
        "S", (), {"startTime": datetime.datetime.now(), "check_limit": lambda *args, **kwargs: (False, False)}
    )()

    # Override speed_multiplier to avoid multi-minute sleeps in CI
    e2e_configs.args.speed_multiplier = 0.01

    result = _run_zero_latency_feed_loop(
        device,
        cognitive_stack["zero_engine"],
        cognitive_stack["nav_graph"],
        e2e_configs,
        session_state,
        "HomeFeed",
        cognitive_stack,
    )

    # Must return CONTEXT_LOST
    assert (
        result == "CONTEXT_LOST"
    ), f"Feed loop returned '{result}' instead of 'CONTEXT_LOST' when Play Store was in foreground."

    # Must have pressed back to attempt recovery
    assert "back" in device.pressed_keys, "Feed loop detected foreign app but never pressed BACK to recover!"
