"""
E2E tests for the Story View behavior.
Ensures the system correctly identifies and clicks the story ring.
"""

import pytest

from GramAddict.core.behaviors import BehaviorContext
from GramAddict.core.behaviors.story_view import StoryViewPlugin


@pytest.mark.live_llm
def test_story_view_clicks_story_ring(make_real_device_with_image, e2e_configs, e2e_cognitive_stack_factory):
    """
    TDD Test: StoryViewPlugin must correctly identify if a story exists
    and trigger the 'tap story ring avatar' navigation.
    """
    xml_path = "tests/fixtures/home_feed_with_ad.xml"

    with open(xml_path, "r", encoding="utf-8") as f:
        xml = f.read()

    # The actual image (home_feed_with_ad.jpg) has story rings at the top,
    # but the XML doesn't contain the specific 'reel_ring' ID that triggers has_story.
    import re

    # We inject it so the plugin knows there is a story, AND we add a content-desc so the Text VLM easily finds it.
    xml_before = re.sub(
        r'resource-id="com\.instagram\.android:id/row_feed_photo_profile_imageview"([^>]+)content-desc="Profile picture of millionlords"',
        r'resource-id="com.instagram.android:id/reel_ring"\1content-desc="Story ring avatar"',
        xml,
    )

    # After tapping the story, the UI should change. We provide story_view_full.xml as the "after" state
    with open("tests/fixtures/story_view_full.xml", "r", encoding="utf-8") as f:
        xml_after = f.read()

    # The sequence of dumps for plugin.execute() calling nav_graph.do:
    # 1. goap.perceive() (xml_before)
    # 2. goap._execute_action find_node (xml_before)
    # 3. goap verification post-click (xml_after)
    # 4. Fallbacks/extras (xml_after, xml_after)
    device = make_real_device_with_image(
        "tests/fixtures/home_feed_with_ad.jpg", [xml_before, xml_after, xml_after, xml_after]
    )

    from GramAddict.core.session_state import SessionState

    # Override only what the test needs — fixture provides all production defaults
    e2e_configs.args.stories_percentage = 100
    e2e_configs.args.stories_count = "1"
    session_state = SessionState(e2e_configs)

    # REAL cognitive stack — all 12 production keys
    cognitive_stack = e2e_cognitive_stack_factory(device)

    ctx = BehaviorContext(
        device=device,
        configs=e2e_configs,
        session_state=session_state,
        username="test_story_user",
        context_xml=xml_before,
        cognitive_stack=cognitive_stack,
    )

    plugin = StoryViewPlugin()

    # Execute should return True because it found a reel ring, attempted to navigate to it,
    # and clicked it. The DeviceFacade records the press.
    result = plugin.execute(ctx)

    assert result.executed is True, f"StoryViewPlugin failed to execute. Reason: {result.metadata.get('reason')}"

    # We can verify that the device facade recorded a click!
    assert len(device.deviceV2.interaction_log) > 0, "No interactions were recorded on the device"

    # Specifically, there should be a click from the find_node or a direct bounds tap
    # We know the VLM should have found the reel ring and clicked it
    click_found = False
    for interaction in device.deviceV2.interaction_log:
        if interaction["action"] == "click":
            click_found = True
            break

    assert click_found, f"Device did not record any click action. Log: {device.deviceV2.interaction_log}"
