# tests/test_wave1_phase_b.py
"""Tests for SemanticConsistencyChecker (wave1 29.3)."""
from __future__ import annotations

import sys
from pathlib import Path
import pytest
import numpy as np

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


def test_semantic_checker_import():
    from llm_guard.features.mechanism_layer import SemanticConsistencyChecker
    assert SemanticConsistencyChecker is not None


def test_semantic_checker_instantiates():
    from llm_guard.features.mechanism_layer import SemanticConsistencyChecker
    checker = SemanticConsistencyChecker(sc_temperature=1.0)
    assert checker.sc_temperature == 1.0


def test_semantic_checker_temperature_zero():
    from llm_guard.features.mechanism_layer import SemanticConsistencyChecker
    checker = SemanticConsistencyChecker(sc_temperature=0.0)
    assert checker.sc_temperature == 0.0


def test_compute_semantic_consistency_returns_float():
    """compute_semantic_consistency uses existing extractor — no API call."""
    from llm_guard.features.mechanism_layer import SemanticConsistencyChecker, MechanismFeatureExtractor
    extractor = MechanismFeatureExtractor()
    checker = SemanticConsistencyChecker(sc_temperature=1.0)
    responses = ["Martin Van Buren was first.", "It was Martin Van Buren.", "Van Buren."]
    score = checker.compute_semantic_consistency(extractor, responses)
    assert isinstance(score, float)
    assert 0.0 <= score <= 1.0


def test_compute_semantic_consistency_single_response():
    """Single response = perfect consistency = 1.0."""
    from llm_guard.features.mechanism_layer import SemanticConsistencyChecker, MechanismFeatureExtractor
    extractor = MechanismFeatureExtractor()
    checker = SemanticConsistencyChecker()
    score = checker.compute_semantic_consistency(extractor, ["Only one answer."])
    assert score == 1.0


def test_compute_semantic_consistency_diverse_responses():
    """Very different answers should have lower consistency than identical answers."""
    from llm_guard.features.mechanism_layer import SemanticConsistencyChecker, MechanismFeatureExtractor
    extractor = MechanismFeatureExtractor()
    checker = SemanticConsistencyChecker()
    identical = ["Martin Van Buren.", "Martin Van Buren.", "Martin Van Buren."]
    diverse = ["Martin Van Buren.", "George Washington was first.", "Abraham Lincoln led the country."]
    score_identical = checker.compute_semantic_consistency(extractor, identical)
    score_diverse   = checker.compute_semantic_consistency(extractor, diverse)
    assert score_identical > score_diverse, (
        f"Identical ({score_identical:.3f}) should > diverse ({score_diverse:.3f})"
    )
