from unittest.mock import MagicMock

from GramAddict.core.resonance_engine import ResonanceEngine


def test_resonance_engine_bootstraps_persona_from_config(monkeypatch):
    """
    TDD Test: When the ResonanceEngine is instantiated with persona_interests,
    it must successfully compute a persona vector and be able to calculate
    meaningful resonance scores (> 0.5 default) for matching content.
    """
    # Mock the Qdrant DBs
    mock_content_db = MagicMock()
    mock_persona_db = MagicMock()

    # Simulate a vector embedding
    def fake_get_embedding(text):
        if not text:
            return None
        # Return a dummy vector
        return [0.1] * 768

    mock_content_db._get_embedding = MagicMock(side_effect=fake_get_embedding)

    # We will simulate cosine similarity calculation.
    # Since both will be [0.1]*768, similarity would be 1.0.
    def fake_calculate_similarity(vec1, vec2):
        if not vec1 or not vec2:
            return 0.5
        return 0.95

    monkeypatch.setattr("GramAddict.core.resonance_engine.ContentMemoryDB", lambda: mock_content_db)
    monkeypatch.setattr("GramAddict.core.resonance_engine.PersonaMemoryDB", lambda: mock_persona_db)
    monkeypatch.setattr("GramAddict.core.resonance_engine.cosine_similarity", fake_calculate_similarity, raising=False)

    # 1. Create with NO persona interests
    engine_blind = ResonanceEngine("test_user", persona_interests=[])
    score_blind = engine_blind.calculate_resonance({"description": "Beautiful mountain sunset"})

    assert score_blind == 0.5, "Blind engine should return exactly 0.5"
    assert engine_blind._persona_vector is None

    # 2. Create WITH persona interests
    engine_smart = ResonanceEngine("test_user", persona_interests=["travel", "landscape"])

    assert engine_smart._persona_vector is not None, "Persona vector must be bootstrapped!"

    # Mocking semantic search behavior in ResonanceEngine:
    # Actually, calculate_resonance uses self.content_memory._get_embedding(text)
    # Let's mock the internal similarity function if it's there.

    # We must ensure that target_audience is properly wired in bot_flow!
    # This test just verifies the engine side, we will also add a test to verify config parsing.
