"""
E2E: Same Post Loop Prevention Regression
============================================
PRODUCTION BUG 2026-04-30:
Bot processed @ehsan.nura 7 times consecutively because:
1. Each interaction cycle failed (follow failed, like failed, username tap failed)
2. perfect_snapping kept swiping to the same post (35x snapping attempts)
3. post_interaction moved to "next post" but snapping brought it right back

The pipeline must detect when it's stuck processing the same post
repeatedly and break out of the loop.

Mock: ONLY the device (XML dumps).
Real: Cognitive stack, PluginRegistry, SessionState, Config.
"""

import os

E2E_FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures")
FIXTURES_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "fixtures")


def _load_fixture(name, e2e=False):
    base = E2E_FIXTURES_DIR if e2e else FIXTURES_DIR
    with open(os.path.join(base, name), "r", encoding="utf-8") as f:
        return f.read()


def test_same_xml_does_not_cause_infinite_snapping(make_real_device_with_xml, e2e_workflow_ctx):
    """
    REGRESSION: When the device always returns the same XML (stuck state),
    perfect_snapping must not endlessly swipe trying to align.

    Simulates: device is stuck showing the same post. After each swipe,
    the XML is identical. Snapping must give up, not loop 35 times.
    """
    # Same XML returned every time — simulates a stuck device
    reels_xml = _load_fixture("reels_feed_dump.xml")
    device = make_real_device_with_xml([reels_xml] * 10)
    results, ctx = e2e_workflow_ctx(device)

    # Perfect snapping must not have swiped more than a reasonable limit
    # In the real bug, it swiped 35 times on the same post
    assert len(device.swipes) <= 10, (
        f"Perfect snapping performed {len(device.swipes)} swipes on identical XML — "
        "this is the infinite snapping loop bug! "
        "Expected max 10 swipes before giving up."
    )


def test_pipeline_does_not_crash_on_repeated_failures(make_real_device_with_xml, e2e_workflow_ctx):
    """
    When multiple plugins fail on the same post (like fails, follow fails,
    username tap fails), the pipeline must still complete without exceptions.
    It should gracefully move to the next post or terminate.
    """
    home_xml = _load_fixture("home_feed_real.xml", e2e=True)
    device = make_real_device_with_xml([home_xml, home_xml, home_xml])
    results, ctx = e2e_workflow_ctx(device)

    # The pipeline must complete (we got results, no exception)
    assert results is not None, "Pipeline crashed!"
    assert len(results) >= 1, "No plugin results returned!"

    # No CONTEXT_LOST should be raised on a normal home feed
    context_lost = any(r.metadata.get("return_code") == "CONTEXT_LOST" for r in results)
    assert not context_lost, "CONTEXT_LOST on a normal home feed — false positive!"
