"""
E2E: Story Loop Foreign App Escape
====================================
Validates that the story binging loop detects a foreign app takeover
(e.g. Play Store opened via story link) and immediately aborts with
CONTEXT_LOST instead of continuing to tap blindly.

Production Bug Reproduction:
    Session: 2026-05-03_18-03-15
    Trace: Frames 14-40 (Instagram Stories) → Frame 41 (com.android.vending)
    Root Cause: _run_zero_latency_stories_loop had no perimeter guard.

Uses the REAL production XML dumps from the 2026-05-03 session trace.
"""

import datetime

from tests.e2e.conftest import E2EDeviceStub, load_fixture_xml


def test_story_loop_escapes_foreign_app(e2e_configs, e2e_cognitive_stack_factory):
    """
    Simulates: Story → Story → Story → Play Store (via swipe-up link).
    The loop must detect com.android.vending and abort immediately.
    """
    from GramAddict.core.bot_flow import _run_zero_latency_stories_loop

    story_xml = load_fixture_xml("story_view_before_linkout.xml")
    play_store_xml = load_fixture_xml("play_store_from_story_link.xml")

    # 3 story iterations → then Play Store appears
    device = E2EDeviceStub([story_xml, story_xml, story_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()})()

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

    result = _run_zero_latency_stories_loop(device, e2e_configs, session_state, cognitive_stack)

    # Must return CONTEXT_LOST, NOT FEED_EXHAUSTED
    assert result == "CONTEXT_LOST", (
        f"Story loop returned '{result}' instead of 'CONTEXT_LOST' when Play Store was in foreground. "
        f"The bot would have tapped blindly on the Play Store! "
        f"This is the exact production bug from 2026-05-03."
    )

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