"""Run locally with pytest test_search_practice.py or on the chapter page."""

from search_practice import cosine, cutoff_report, gate, rank


def test_cosine_direction_not_length():
    assert abs(cosine([1, 1], [2, 2]) - 1) < 1e-9
    assert abs(cosine([1, 0], [0, 1])) < 1e-9


def test_zero_vector_and_shape():
    assert cosine([0, 0], [1, 2]) == 0
    try:
        cosine([1], [1, 0])
    except ValueError:
        pass
    else:
        assert False, "different dimensions need an explicit error"


def test_rank_keeps_ties_in_input_order():
    entries = [("billing", [1, 0]), ("data", [1, 0]), ("support", [0, 1])]
    assert rank([1, 0], entries) == ["billing", "data", "support"]


def test_cutoff_keeps_the_right_low_score():
    assert gate(0.38, 0.30) == "answer"
    assert gate(0.38, 0.40) == "handoff"
    assert gate(0.30, 0.30) == "answer"


def test_cutoff_cannot_fix_confident_wrong_match():
    assert gate(0.66, 0.30) == "answer"  # wrong data-policy result
    assert gate(0.38, 0.30) == "answer"  # right refund-policy result


# The seven recorded top scores from the chapter (text-embedding-3-small):
# five questions the FAQ answers, then pasta and the capital of France.
RECORDED = [(0.7236, True), (0.6596, True), (0.4727, True), (0.4349, True), (0.3755, True),
            (0.2164, False), (0.1095, False)]


def test_calibrate_the_cutoff_on_recorded_scores():
    assert cutoff_report(RECORDED, 0.40) == {"kept": 4, "stopped": 2, "false_handoffs": 1}
    assert cutoff_report(RECORDED, 0.30) == {"kept": 5, "stopped": 2, "false_handoffs": 0}
    assert cutoff_report(RECORDED, 0.20) == {"kept": 5, "stopped": 1, "false_handoffs": 0}
