from unittest.mock import MagicMock

from GramAddict.core.telepathic_engine import TelepathicEngine


def test_learnable_fast_paths_use_qdrant(monkeypatch):
    """
    TDD Test: The TelepathicEngine must NOT rely solely on hardcoded fast paths.
    It should store and retrieve high-confidence fast paths (like resource-IDs for tabs)
    from the UIMemoryDB (Qdrant).
    """
    # Use direct instantiation to bypass any singleton mock leakage from previous tests
    TelepathicEngine.reset()
    engine = TelepathicEngine()

    # Mock UIMemoryDB
    mock_memory = MagicMock()
    monkeypatch.setattr(engine, "ui_memory", mock_memory, raising=False)

    # 1. When Qdrant HAS a mapping for 'tap profile tab', it should use it.
    mock_memory.retrieve_memory.return_value = {
        "resource_id": "com.instagram.android:id/profile_tab_learned",
        "action": "tap",
        "confidence": 0.95,
    }

    viable_nodes = [
        {"resource_id": "com.instagram.android:id/profile_tab_learned", "x": 10, "y": 20, "semantic_string": "profile"},
        {"resource_id": "com.instagram.android:id/feed_tab", "x": 30, "y": 40, "semantic_string": "feed"},
    ]

    # We pass viable_nodes because the core_nav fast path scans nodes
    result = engine._core_navigation_fast_path("tap profile tab", viable_nodes)

    assert result is not None, "Should use learned path from memory"
    assert result["x"] == 10, "Should select the node matching LEARNED resource-id, not hardcoded!"
    assert result["source"] == "qdrant_nav", "Source should be marked as Qdrant memory"

    # 2. When Qdrant does NOT have a mapping, it MUST NOT fall back to hardcoded defaults.
    # It must return None to force the system to evaluate semantics autonomously (Blank Start).
    mock_memory.retrieve_memory.return_value = None

    result2 = engine._core_navigation_fast_path("tap home tab", viable_nodes)

    assert result2 is None, "Should NOT fall back to default seed; must enforce Blank Start!"
