"""
E2E tests for Ad Guard and anomaly handling.
Ensures the system correctly identifies and skips sponsored content.
"""

import pytest

from GramAddict.core.behaviors import BehaviorContext
from GramAddict.core.behaviors.ad_guard import AdGuardPlugin
from GramAddict.core.telepathic_engine import TelepathicEngine


@pytest.mark.live_llm
def test_ad_guard_detects_sponsored_post(make_real_device_with_image):
    """
    TDD Test: AdGuardPlugin must successfully identify a sponsored post
    in a real feed using the TelepathicEngine.
    """
    xml_path = "tests/fixtures/home_feed_with_ad.xml"
    jpg_path = "tests/fixtures/home_feed_with_ad.jpg"

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

    device = make_real_device_with_image(jpg_path)
    device.dump_hierarchy = lambda: xml

    import types

    from GramAddict.core.config import Config
    from GramAddict.core.session_state import SessionState

    configs = Config(first_run=True)
    configs.args = types.SimpleNamespace()
    session_state = SessionState(configs)

    telepathic = TelepathicEngine.get_instance()

    ctx = BehaviorContext(
        device=device,
        configs=configs,
        session_state=session_state,
        username="test_ad_user",
        context_xml=xml,
        cognitive_stack={"telepathic": telepathic},
    )

    plugin = AdGuardPlugin()

    result = plugin.execute(ctx)

    # Executed should be True, meaning it triggered and took action (scrolled past the ad)
    assert result.executed is True, "AdGuardPlugin failed to detect the sponsored post!"
    assert result.should_skip is True, "AdGuardPlugin executed but did not set should_skip"
