"""Variance / within_tolerance boundary tests (CONTRACT §5)."""

from __future__ import annotations

from app.matching.variance import tolerance_band, variance, within_tolerance


def test_variance_rounds_to_configured_places():
    assert variance(100.126, 100.0, 2) == 0.13
    assert variance(100.00, 40.00, 2) == 60.0
    assert variance(40.0, 50.0, 2) == -10.0


def test_absolute_tolerance_dominates_for_small_amounts():
    # planned 100: rel band = 0.5 -> abs band 1.0 wins.
    assert tolerance_band(100, 1.0, 0.005) == 1.0
    assert within_tolerance(100.0, 100.9, 1.0, 0.005)  # 0.9 <= 1.0
    assert not within_tolerance(100.0, 98.5, 1.0, 0.005)  # 1.5 > 1.0


def test_relative_tolerance_dominates_for_large_amounts():
    # planned 15000: rel band = 75 -> beats abs 1.0.
    assert tolerance_band(15000, 1.0, 0.005) == 75.0
    assert within_tolerance(15000.0, 15000.40, 1.0, 0.005)  # 0.40 <= 75
    assert within_tolerance(15000.0, 15074.0, 1.0, 0.005)  # 74 <= 75
    assert not within_tolerance(15000.0, 15080.0, 1.0, 0.005)  # 80 > 75


def test_exact_boundary_is_inclusive():
    assert within_tolerance(1000.0, 999.0, 1.0, 0.0)  # variance 1.0 == abs tol
    assert not within_tolerance(1000.0, 998.99, 1.0, 0.0)  # 1.01 > 1.0
