# retoor <retoor@molodetz.nl>

from devplacepy.services.deepsearch.citations import link_citations


def test_single_marker_links_to_source_anchor():
    out = str(link_citations("Server components are default [1].", 5))
    assert '<a class="ds-cite" href="#ds-source-1" data-cite="1">[1]</a>' in out


def test_consecutive_and_range_markers_all_link():
    out = str(link_citations("leaving TODOs in production [3][9][1-2].", 12))
    for n in (1, 2, 3, 9):
        assert f'href="#ds-source-{n}"' in out
    assert "[1-2]" not in out


def test_out_of_range_marker_is_not_linked():
    out = str(link_citations("cited [99] and [3]", 5))
    assert "#ds-source-99" not in out
    assert "[99]" in out
    assert 'href="#ds-source-3"' in out


def test_markers_inside_code_and_anchors_are_left_alone():
    html = 'see <a href="http://x">link [3]</a> and <code>arr[3]</code> and text [3]'
    out = str(link_citations(html, 12))
    assert out.count('class="ds-cite"') == 1
    assert "<code>arr[3]</code>" in out
    assert '<a href="http://x">link [3]</a>' in out


def test_range_clamped_to_source_count():
    out = str(link_citations("range [4-6]", 5))
    assert 'href="#ds-source-4"' in out
    assert 'href="#ds-source-5"' in out
    assert "#ds-source-6" not in out


def test_zero_sources_returns_input_unchanged():
    assert str(link_citations("text [1]", 0)) == "text [1]"


def test_reversed_range_left_alone():
    out = str(link_citations("weird [5-2] marker", 10))
    assert out == "weird [5-2] marker"
