from unittest.mock import MagicMock, patch

from GramAddict.core.compiler_engine import VLMCompilerEngine


def test_compiler_intent_list_handling():
    """
    Test that VLMCompilerEngine gracefully handles intents that are lists,
    which can happen when Shadow Mode submits ['row_feed', 'button_like'].
    """
    mock_device = MagicMock()
    compiler = VLMCompilerEngine(mock_device)

    # We submit a string representation of a list as intent, simulating Dojo's behavior:
    # dojo.submit_snapshot(heuristic_name=str(expected_signature), ... intent_prompt=f"... {expected_signature}")
    raw_list_intent = "['row_feed', 'button_like']"

    # We want the prompt to be clean. Let's intercept the prompt going to the LLM.
    with patch("GramAddict.core.llm_provider.query_telepathic_llm") as mock_query:
        # Mock LLM to return a valid JSON so the rest of the flow can execute
        mock_query.return_value = '{"rule_type": "regex", "target_attribute": "resource-id", "pattern": ".*row_feed.*", "confidence": 0.95, "reasoning": "Test"}'

        result = compiler.generate_heuristic(raw_list_intent, "<xml/>")

        # Verify the prompt is properly sanitized
        called_args = mock_query.call_args
        assert called_args is not None

        user_prompt = called_args.kwargs["user_prompt"]

        # User prompt should contain a readable description, NOT a python list string.
        # e.g., if intent has "button_like", prompt should ask for it clearly.
        assert "TARGET INTENT" in user_prompt
        assert "row_feed" in user_prompt
        assert "button_like" in user_prompt
        assert "['" not in user_prompt  # No python list syntax!
        assert result is not None
        assert result["pattern"] == ".*row_feed.*"
