"""
TDD Tests for Zero-Hardcode Screen Classification and Situational Awareness
"""

import os
import sys
from unittest.mock import patch

import pytest

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))

from GramAddict.core.goap import ScreenIdentity, ScreenType


@pytest.fixture
def mock_screen_memory():
    with patch("GramAddict.core.qdrant_memory.ScreenMemoryDB") as mock_db:
        instance = mock_db.return_value
        instance.is_connected = True
        yield instance


@pytest.fixture
def mock_query_llm():
    with patch("GramAddict.core.llm_provider.query_llm") as mock_llm:
        yield mock_llm


def test_classify_screen_uses_memory(mock_screen_memory, mock_query_llm):
    """
    Test that _classify_screen FIRST tries to hit the ScreenMemoryDB.
    """
    si = ScreenIdentity("testbot")

    # Mock that memory ALREADY knows this screen
    mock_screen_memory.get_screen_type.return_value = ScreenType.MODAL.name

    # We pass random strings that would previously fail or hit hardcoded checks
    res = si._classify_screen(
        ids=set(),
        descs=[],
        texts=["totally ambiguous text"],
        selected_tab=None,
        desc_lower="",
        text_lower="",
        ids_str="random_id",
        signature="MOCK_SIGNATURE",
    )

    assert res == ScreenType.MODAL
    mock_screen_memory.get_screen_type.assert_called_once_with("MOCK_SIGNATURE", similarity_threshold=0.92)
    # Should not fall back to LLM if memory hits
    mock_query_llm.assert_not_called()


def test_classify_screen_uses_llm_fallback_and_learns(mock_screen_memory, mock_query_llm):
    """
    Test that if memory misses, it uses LLM fallback and caches the result.
    """
    si = ScreenIdentity("testbot")
    mock_screen_memory.get_screen_type.return_value = None
    mock_query_llm.return_value = {"response": "HOME_FEED"}

    res = si._classify_screen(
        ids={"random"},
        descs=[],
        texts=[],
        selected_tab=None,
        desc_lower="",
        text_lower="",
        ids_str="random",
        signature="MOCK_SIGNATURE_2",
    )

    assert res == ScreenType.HOME_FEED
    mock_query_llm.assert_called_once()
    mock_screen_memory.store_screen.assert_called_once_with("MOCK_SIGNATURE_2", "HOME_FEED")
