from tests.constants import ALPHABET, LANGUAGE_FILES, PRECISION


def test_kl_div():
    from src.enhanced_occurrence_frequencies import (
        read_text, compute_occurrence_frequencies, kl_divergence
    )

    try:
        kl_divergence({}, {'a': 1.0})
        raise Exception("should raise an error")
    except Exception:
        pass

    ofs = {
        lang: compute_occurrence_frequencies(read_text(file), ALPHABET)
        for lang, file in LANGUAGE_FILES.items()
    }

    for (lang_1, lang_2, kl_div) in [
        ("french", "french", 0.0),
        ("english", "english", 0.0),
        ("spanish", "spanish", 0.0),
        ("german", "german", 0.0),
        ("french", "english", 0.33651188482999345),
        ("english", "french", 0.33651188482999345),
        ("french", "spanish", 0.09856433854191257),
        ("spanish", "french", 0.09856433854191257),
        ("french", "german", 0.3824577488813984),
        ("german", "french", 0.3824577488813984),
        ("english", "spanish", 0.3660292247415318),
        ("spanish", "english", 0.3660292247415318),
        ("english", "german", 0.19829847695413377),
        ("german", "english", 0.19829847695413377),
        ("german", "spanish", 0.4735746888937046),
        ("spanish", "german", 0.4735746888937046),
    ]:
        div = kl_divergence(ofs[lang_1], ofs[lang_2])
        assert abs(div - kl_div) <= PRECISION, (
            f"KL divergence should be closer to {kl_div}, found {div}, delta "
            f"= {abs(div - kl_div)}"
        )
