from unittest.mock import MagicMock, patch

import pytest

from GramAddict.core.telepathic_engine import TelepathicEngine


@pytest.fixture
def mock_device():
    device = MagicMock()
    device.get_screenshot_b64.return_value = "fake_base64_image_data"

    # Mock args
    class Args:
        ai_telepathic_model = "test-model"
        ai_telepathic_url = "http://test-url"

    device.args = Args()
    return device


@patch("GramAddict.core.llm_provider.query_llm")
def test_evaluate_post_vibe_rejects_poor_quality(mock_query_llm, mock_device):
    engine = TelepathicEngine()

    persona_interests = ["aesthetic architecture", "minimalism"]

    # Mock VLM response to reject the post
    mock_query_llm.return_value = {
        "response": '{"quality_score": 3, "matches_niche": false, "reason": "Generic text meme, no architectural elements."}'
    }

    result = engine.evaluate_post_vibe(device=mock_device, persona_interests=persona_interests)

    # Verify screenshot was evaluated
    assert mock_device.get_screenshot_b64.called
    assert mock_query_llm.called

    # Verify the structured response parsing
    assert result is not None
    assert result["quality_score"] == 3
    assert result["matches_niche"] is False
    assert "Generic text meme" in result["reason"]


@patch("GramAddict.core.llm_provider.query_llm")
def test_evaluate_post_vibe_accepts_high_quality(mock_query_llm, mock_device):
    engine = TelepathicEngine()

    persona_interests = ["aesthetic architecture", "minimalism"]

    # Mock VLM response to accept the post
    mock_query_llm.return_value = {
        "response": '{"quality_score": 9, "matches_niche": true, "reason": "Beautiful cohesive architectural shot."}'
    }

    result = engine.evaluate_post_vibe(device=mock_device, persona_interests=persona_interests)

    # Verify screenshot was evaluated
    assert mock_device.get_screenshot_b64.called
    assert mock_query_llm.called

    # Verify the structured response parsing
    assert result is not None
    assert result["quality_score"] == 9
    assert result["matches_niche"] is True
    assert "Beautiful cohesive" in result["reason"]


@patch("GramAddict.core.llm_provider.query_llm")
def test_evaluate_post_vibe_handles_invalid_json(mock_query_llm, mock_device):
    engine = TelepathicEngine()

    persona_interests = ["aesthetic architecture", "minimalism"]

    # Mock VLM response with garbage output
    mock_query_llm.return_value = {"response": "I think this is a nice picture but I forgot to output JSON."}

    result = engine.evaluate_post_vibe(device=mock_device, persona_interests=persona_interests)

    # Verify fallback to None on error
    assert result is None
