"""Tests for GroundednessCheck."""

from unittest.mock import MagicMock, patch

import pytest

from ai_qa.checks.groundedness import GroundednessCheck
from ai_qa.core.context import Context
from ai_qa.exceptions import ContextValidationError


def test_groundedness_check_name():
    """Test GroundednessCheck has correct name."""
    check = GroundednessCheck()
    assert check.name == "groundedness"


def test_groundedness_check_requires_llm():
    """Test GroundednessCheck requires_llm property."""
    check = GroundednessCheck()
    assert check.requires_llm is True


@patch("ai_qa.checks.groundedness.get_provider")
def test_groundedness_fully_grounded(mock_get_provider):
    """Test fully grounded output."""
    check = GroundednessCheck()
    ctx = Context(output="Python is a programming language",
        context=["Python is a high-level programming language"],
    )

    mock_provider = MagicMock()
    mock_provider.judge.return_value = {
        "score": 1.0,
        "evidence": "All claims grounded",
    }
    mock_get_provider.return_value = mock_provider

    result = check.evaluate(ctx)
    assert result.score == 1.0
    assert result.passed


@patch("ai_qa.checks.groundedness.get_provider")
def test_groundedness_partially_grounded(mock_get_provider):
    """Test partially grounded output."""
    check = GroundednessCheck(threshold=0.7)
    ctx = Context(output="Python is a programming language. It costs $100.",
        context=["Python is a high-level programming language"],
    )

    mock_provider = MagicMock()
    mock_provider.judge.return_value = {
        "score": 0.5,
        "evidence": "50% of claims grounded",
    }
    mock_get_provider.return_value = mock_provider

    result = check.evaluate(ctx)
    assert result.score == 0.5
    assert not result.passed


def test_groundedness_no_context():
    """Test error when context missing."""
    check = GroundednessCheck()
    ctx = Context(output="Some output")
    with pytest.raises(ContextValidationError):
        check.evaluate(ctx)


def test_groundedness_no_output():
    """Test error when output missing."""
    from unittest.mock import MagicMock

    check = GroundednessCheck()
    ctx = MagicMock()
    ctx.output = None
    ctx.context = ["Some context"]
    with pytest.raises(ContextValidationError):
        check.evaluate(ctx)
