"""
E2E: GOAP Trap Recovery
========================
Validates that the GOAP engine can properly escape "completely trapped" states
by forcing an app restart, and that the internal failure states are correctly
purged so it doesn't immediately trap itself again on the next iteration.
"""

from GramAddict.core.goap import GoalExecutor
from tests.e2e.conftest import load_fixture_xml
from tests.e2e.device_emulator import create_emulator_facade


def test_goap_recovers_from_trapped_state_with_restart(monkeypatch):
    """
    Simulates a broken UI where an action repeatedly fails.
    Verifies that GOAP triggers 'force start instagram', and successfully
    clears its tracking arrays (action_failures, etc.) to start fresh,
    avoiding an infinite restart loop.
    """
    xml = load_fixture_xml("home_feed_real.xml")

    # Single-state emulator with no transitions → UI never changes.
    # This forces actions to fail repeatedly, triggering GOAP trap detection.
    device, emulator = create_emulator_facade("trapped", {"trapped": xml}, {}, monkeypatch)

    goap = GoalExecutor.get_instance(device, bot_username="testuser")
    goap.action_failures.clear()

    # We want to ask it to reach REELS_FEED.
    # Since the UI never changes, 'tap reels tab' will fail.
    # It will fail twice, get masked, GOAP gets trapped, triggers restart.
    # We set max_steps to a small number so it doesn't loop forever in the test.
    # We just want to see that AFTER the restart, it tries 'tap reels tab' again,
    # meaning it cleared the state.

    goap.achieve("open reels", max_steps=10)

    # It should have tried 'tap reels tab' twice, failed both times,
    # then triggered 'force start instagram'.
    # Because of the fix, after the restart, it should have cleared failures
    # and tried 'tap reels tab' AGAIN.

    assert len(emulator.app_starts) > 0, "GOAP never attempted to force restart Instagram when trapped!"

    # Count how many times it clicked the screen (trying to tap the reels tab)
    reels_attempts = len(emulator.clicks)

    assert reels_attempts > 2, (
        f"GOAP got trapped, restarted, but never tried the action again! "
        f"It only tried {reels_attempts} times, meaning the memory leak is still there. "
    )

    # If the bug was present, it would only try 'tap reels tab' 2 times, mask it forever,
    # and then spam 'force start instagram' for the remaining steps.
    # With the fix, it tries 2 times, restarts, tries 2 times, restarts, etc.
