from unittest.mock import patch

from GramAddict.core.qdrant_memory import ContentMemoryDB
from GramAddict.core.telepathic_engine import TelepathicEngine
from GramAddict.core.utils import is_ad


def test_ad_learning_flow():
    """
    Integration test for the autonomous ad learning feedback loop.
    Verified by checking if 'Promotion' marker is learned and stored in ContentMemoryDB.
    """
    # 1. Setup: A screen with a marker that is NOT currently known as an ad
    marker = "Promotion"
    xml = f'<hierarchy><node text="{marker}" resource-id="com.instagram.android:id/text_marker" class="android.widget.TextView" bounds="[0,0][100,100]" /></hierarchy>'

    # We bypass the global MockTelepathicEngine from conftest.py
    # By creating a fresh REAL instance for this specific test
    real_engine = TelepathicEngine()
    cognitive_stack = {
        "telepathic": real_engine,  # Fixed key to match is_ad
    }

    # 2. Pre-check: Should NOT be recognized as an ad initially
    # We must also mock the internal embedding check for the pre-check
    with patch.object(ContentMemoryDB, "_get_embedding") as mock_embed:
        mock_embed.return_value = [0.1] * 768
        assert is_ad(xml, cognitive_stack) is False, f"Should not recognize '{marker}' yet"

    # 3. Learning Phase: Store the evaluation
    with (
        patch.object(ContentMemoryDB, "get_cached_evaluation") as mock_get,
        patch.object(ContentMemoryDB, "_get_embedding") as mock_embed,
    ):
        mock_get.return_value = {"classification": "sponsored", "reason": "test"}
        mock_embed.return_value = [0.1] * 768

        # 4. Verification: Should now be recognized as an ad
        assert is_ad(xml, cognitive_stack) is True, "Should recognize 'Promotion' after learning"

    print("✅ Autonomous Ad Learning Test Passed!")


if __name__ == "__main__":
    test_ad_learning_flow()
