"""
Production Bug Regression: Play Store Trap (2026-05-03)
========================================================
Session: 2026-05-03_18-03-15
Trace: Frames 14-40 (Instagram Stories) → Frame 41 (com.android.vending)

Root Cause: Story loop had no perimeter guard. A story's swipe-up link
opened the Play Store, and the bot continued tapping at (w*0.85, h*0.5)
on Play Store UI for 5+ iterations until user killed the process.

This test uses the EXACT production XML dumps to validate:
1. ScreenIdentity correctly classifies Play Store as FOREIGN_APP
2. SAE correctly classifies Play Store as OBSTACLE_FOREIGN_APP
3. Story frame before the linkout is correctly classified as STORY_VIEW
"""

from GramAddict.core.perception.screen_identity import ScreenIdentity, ScreenType
from GramAddict.core.situational_awareness import SituationalAwarenessEngine, SituationType
from tests.e2e.conftest import E2EDeviceStub, load_fixture_xml


class TestPlayStoreTrapRegression:
    def test_screen_identity_classifies_play_store_as_foreign(self):
        """ScreenIdentity must classify com.android.vending as FOREIGN_APP."""
        xml = load_fixture_xml("play_store_from_story_link.xml")
        sid = ScreenIdentity("testuser")
        result = sid.identify(xml)
        assert result["screen_type"] == ScreenType.FOREIGN_APP, (
            f"ScreenIdentity classified Play Store as {result['screen_type'].value}! "
            f"This is the exact production bug from 2026-05-03."
        )

    def test_sae_classifies_play_store_as_obstacle_foreign_app(self):
        """SAE must classify com.android.vending as OBSTACLE_FOREIGN_APP."""
        xml = load_fixture_xml("play_store_from_story_link.xml")
        device = E2EDeviceStub([xml])
        SituationalAwarenessEngine.reset()
        sae = SituationalAwarenessEngine(device)
        result = sae.perceive(xml)
        assert result == SituationType.OBSTACLE_FOREIGN_APP, (
            f"SAE classified Play Store as {result.value}! " f"Exact production bug regression from 2026-05-03."
        )

    def test_story_view_before_linkout_is_story(self):
        """The last story frame before the Play Store must be STORY_VIEW."""
        xml = load_fixture_xml("story_view_before_linkout.xml")
        sid = ScreenIdentity("testuser")
        result = sid.identify(xml)
        assert result["screen_type"] == ScreenType.STORY_VIEW, (
            f"Frame before Play Store was classified as {result['screen_type'].value}, "
            f"not STORY_VIEW. This could cause false positives."
        )
