"""Tests for self-peptide reference set and overlap scoring."""
import pytest

from peptidegym.peptide.selfpeptide import HUMAN_4MERS, max_kmer_overlap
from peptidegym.peptide.properties import AMINO_ACIDS


def test_human_4mers_is_frozenset():
    """HUMAN_4MERS should be an immutable frozenset."""
    assert isinstance(HUMAN_4MERS, frozenset)


def test_human_4mers_not_empty():
    """The reference set should contain a substantial number of 4-mers."""
    assert len(HUMAN_4MERS) > 100


def test_human_4mers_all_length_4():
    """Every element should be a 4-character string of valid amino acids."""
    for kmer in HUMAN_4MERS:
        assert len(kmer) == 4
        assert all(aa in AMINO_ACIDS for aa in kmer)


def test_max_kmer_overlap_returns_float():
    """Function should return a float."""
    result = max_kmer_overlap("ALAAAAAAV")
    assert isinstance(result, float)


def test_max_kmer_overlap_range():
    """Overlap should be in [0, 1]."""
    result = max_kmer_overlap("ALAAAAAAV")
    assert 0.0 <= result <= 1.0


def test_max_kmer_overlap_short_sequence():
    """Sequence shorter than k=4 should return 0.0."""
    assert max_kmer_overlap("ALA") == pytest.approx(0.0)
    assert max_kmer_overlap("A") == pytest.approx(0.0)
    assert max_kmer_overlap("") == pytest.approx(0.0)


def test_max_kmer_overlap_known_common_kmer():
    """Sequence built from the reference set should show nonzero overlap.

    We pick the first kmer from HUMAN_4MERS and embed it in a longer peptide.
    """
    kmer = next(iter(HUMAN_4MERS))
    # Pad with flanking residues so the sequence is at least 8 AA
    seq = "AA" + kmer + "AA"
    result = max_kmer_overlap(seq)
    assert result > 0.0, f"Expected overlap > 0 for sequence containing {kmer}"


def test_max_kmer_overlap_rare_sequence():
    """Random rare sequence may have zero overlap — should not crash."""
    # WWWW is uncommon in the human proteome
    result = max_kmer_overlap("WWWWWWWW")
    assert 0.0 <= result <= 1.0
