"""
Hallucination Guard Tests
Tests the Visual Intent Resolver on Hallucination Guards.
"""

import pytest

from GramAddict.core.perception.intent_resolver import IntentResolver
from GramAddict.core.perception.spatial_parser import SpatialParser


@pytest.mark.live_llm
def test_no_hallucination_missing_button(make_real_device_with_image):
    # If we ask for a button that doesn't exist, it MUST return None, not hallucinate.
    xml_path = "tests/fixtures/dm_inbox_dump.xml"
    jpg_path = "tests/fixtures/dm_inbox_dump.jpg"

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

    parser = SpatialParser()
    root = parser.parse(xml)
    candidates = parser.get_clickable_nodes(root)

    device = make_real_device_with_image(jpg_path)
    resolver = IntentResolver()

    # Intentionally asking for 'Follow' on the DM Inbox screen, which definitely does not have it.
    result = resolver.resolve("tap 'Follow' button", candidates, device)

    assert (
        result is None
    ), f"VLM hallucinated an element! It picked id='{result.resource_id}', desc='{result.content_desc}'"


@pytest.mark.live_llm
def test_vlm_must_not_hallucinate_profile_targets(make_real_device_with_image):
    """
    BENCHMARK: Ensures the TelepathicEngine does NOT hallucinate "following list"
    when the element is missing or when the VLM tries to guess (e.g., picking "Grid view").
    """
    from GramAddict.core.telepathic_engine import TelepathicEngine

    # Use a dump that does NOT have a clear following button (e.g., home feed)
    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)
    engine = TelepathicEngine.get_instance()

    # Try to resolve 'tap following list' on a screen where it doesn't exist
    # Use quotes around 'following' to ensure Semantic Guard is strictly applied
    result = engine.find_best_node(xml, "tap 'following' list", device=device, track=False)

    assert (
        result is None or result.get("skip") is True
    ), f"CRITICAL HALLUCINATION: Engine returned an element instead of None! Result: {result}"
