# tests/test_wave2_visual.py
"""Tests for VisualCaptionBridge (wave2 29.4)."""
from __future__ import annotations

import sys
from pathlib import Path
import pytest

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))


def test_import():
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    assert VisualCaptionBridge is not None


def test_instantiates():
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    bridge = VisualCaptionBridge()
    assert bridge is not None


def test_score_grounding_text_mode_returns_float():
    """Text mode: use image_description instead of image_path."""
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    bridge = VisualCaptionBridge()
    score = bridge.score_grounding(
        agent_text="Paris is the capital of France.",
        image_description="A question about the capital city of France.",
    )
    assert isinstance(score, float)
    assert 0.0 <= score <= 1.0


def test_score_grounding_raises_if_neither_provided():
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    bridge = VisualCaptionBridge()
    with pytest.raises(ValueError):
        bridge.score_grounding(agent_text="some answer")


def test_score_grounding_relevant_higher_than_irrelevant():
    """Relevant answer should have higher grounding than irrelevant answer."""
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    bridge = VisualCaptionBridge()
    question = "A diagram showing the Pythagorean theorem: a^2 + b^2 = c^2"
    relevant_answer = "By the Pythagorean theorem, c equals the square root of a squared plus b squared."
    irrelevant_answer = "The population of France is approximately 67 million people."
    score_relevant   = bridge.score_grounding(relevant_answer, image_description=question)
    score_irrelevant = bridge.score_grounding(irrelevant_answer, image_description=question)
    assert score_relevant > score_irrelevant, (
        f"Relevant ({score_relevant:.3f}) should > irrelevant ({score_irrelevant:.3f})"
    )


def test_score_grounding_identical_texts_high_score():
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    bridge = VisualCaptionBridge()
    text = "The graph shows exponential growth."
    score = bridge.score_grounding(text, image_description=text)
    assert score > 0.8, f"Identical texts should have score > 0.8, got {score:.3f}"


def test_embed_text_returns_array():
    from llm_guard.features.visual_caption_bridge import VisualCaptionBridge
    import numpy as np
    bridge = VisualCaptionBridge()
    emb = bridge._embed_text("Hello world")
    assert isinstance(emb, np.ndarray)
    assert emb.ndim == 1
    assert emb.shape[0] > 0
