"""
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


@pytest.mark.live_llm
def test_ad_guard_detects_sponsored_post(make_real_device_with_image, e2e_configs, e2e_cognitive_stack_factory):
    """
    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, xml)

    from GramAddict.core.session_state import SessionState

    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_ad_user",
        context_xml=xml,
        cognitive_stack=cognitive_stack,
    )

    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"
