import textwrap
from typing import TYPE_CHECKING

from debputy.lsp.languages.lsp_debian_changelog import _debian_changelog_links
from lint_tests.lint_tutil import te_range_to_text

if TYPE_CHECKING:
    import lsprotocol.types as types
else:
    import debputy.lsprotocol.types as types

from lsp_tests.lsp_tutil import put_doc_no_cursor

try:
    from pygls.server import LanguageServer

    from debputy.lsp.languages.lsp_debian_rules import debian_rules_completions
    from debputy.lsp.debputy_ls import DebputyLanguageServer

    HAS_PYGLS = True
except ImportError:
    HAS_PYGLS = False


def _doc_link_req(uri: str) -> types.DocumentLinkParams:
    return types.DocumentLinkParams(types.TextDocumentIdentifier(uri))


def test_basic_debian_changelog_bug_links(ls: "DebputyLanguageServer") -> None:
    file_uri = "file:///nowhere/debian/changelog"
    text = textwrap.dedent(
        """\
        debputy (0.1.67) unstable; urgency=medium

          * debputy: some entry without bug links
          * debputy: Fix crash on creating dbgsym packages and other cases,
            where `debputy` would include a symlink in the package without
            a FS backed symlink behind it.
            Thanks to Andrea Pappacoda <tachi@debian.org> (Closes: #1100154)
          * This entry closes many bugs but this line does not have any.
            closes: bug 123456, # 98765
          * Also, you might be interested to see #564737 for this entry.

         -- Niels Thykier <niels@thykier.net>  Thu, 13 Mar 2025 16:50:42 +0000
        """
    )

    put_doc_no_cursor(
        ls,
        file_uri,
        "debian/changelog",
        text,
    )
    lines = text.splitlines(keepends=True)

    links = _debian_changelog_links(
        ls,
        _doc_link_req(file_uri),
    )
    print(links)
    assert links is not None
    assert len(links) == 4
    link_1, link_2, link_3, link_4 = links

    assert te_range_to_text(lines, link_1.range) == "#1100154"
    assert link_1.target == "https://bugs.debian.org/1100154"

    assert te_range_to_text(lines, link_2.range) == "bug 123456"
    assert link_2.target == "https://bugs.debian.org/123456"

    assert te_range_to_text(lines, link_3.range) == "# 98765"
    assert link_3.target == "https://bugs.debian.org/98765"

    assert te_range_to_text(lines, link_4.range) == "#564737"
    assert link_4.target == "https://bugs.debian.org/564737"
