"""
Engagement Navigation Tests
Tests the Visual Intent Resolver on Engagement workflows like saving posts and commenting.
"""

import pytest

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


def run_workflow_test(fixture_base_name, intent, expected_desc_or_id, make_real_device_with_image):
    xml_path = f"tests/fixtures/{fixture_base_name}.xml"
    jpg_path = f"tests/fixtures/{fixture_base_name}.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()

    # Execute real LLM call, NO MOCKING
    result = resolver.resolve(intent, candidates, device)

    assert result is not None, f"VLM returned None for '{intent}'"

    rid = (result.resource_id or "").lower()
    desc = (result.content_desc or "").lower()
    text = (result.text or "").lower()

    matched = False
    for expected in expected_desc_or_id.split("|"):
        expected = expected.strip().lower()
        if expected in rid or expected in desc or expected in text:
            matched = True
            break

    assert matched, (
        f"VLM picked wrong element! Expected one of '{expected_desc_or_id}', "
        f"but got id='{rid}', desc='{desc}', text='{text}'"
    )


@pytest.mark.live_llm
def test_carousel_save(make_real_device_with_image):
    run_workflow_test("carousel_post_dump", "tap 'Add to Saved' button", "saved", make_real_device_with_image)


@pytest.mark.live_llm
def test_comment_sheet_input(make_real_device_with_image):
    run_workflow_test("comment_sheet", "write a comment", "comment", make_real_device_with_image)
