import textwrap
from typing import TYPE_CHECKING

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

from lsp_tests.lsp_tutil import put_doc_with_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 _complete_at_req(uri: str, cursor_pos: types.Position) -> types.CompletionParams:
    return types.CompletionParams(types.TextDocumentIdentifier(uri), cursor_pos)


def test_basic_debian_rules_completer_include(ls: "DebputyLanguageServer") -> None:
    file_uri = "file:///nowhere/debian/rules"

    cursor_pos = put_doc_with_cursor(
        ls,
        file_uri,
        "debian/rules",
        "include <CURSOR>",
    )

    completions = debian_rules_completions(
        ls,
        _complete_at_req(file_uri, cursor_pos),
    )
    assert isinstance(completions, list)
    keywords = {m.label: m for m in completions}
    assert "/usr/share/dpkg/default.mk" in keywords

    cursor_pos = put_doc_with_cursor(
        ls,
        file_uri,
        "debian/rules",
        textwrap.dedent(
            """\
        include /usr/share/<CURSOR>dpkg/default.m
"""
        ),
    )

    completions = debian_rules_completions(
        ls,
        _complete_at_req(file_uri, cursor_pos),
    )
    assert isinstance(completions, list)
    keywords = {m.label: m for m in completions}
    assert "/usr/share/dpkg/default.mk" in keywords

    cursor_pos = put_doc_with_cursor(
        ls,
        file_uri,
        "debian/rules",
        textwrap.dedent(
            """\
        include /usr/share/dpkg/default.mk<CURSOR>
"""
        ),
    )

    completions = debian_rules_completions(
        ls,
        _complete_at_req(file_uri, cursor_pos),
    )
    # No completions (it matches a known value)
    assert not completions

    cursor_pos = put_doc_with_cursor(
        ls,
        file_uri,
        "debian/rules",
        textwrap.dedent(
            """\
        include /usr foo<CURSOR>
"""
        ),
    )

    completions = debian_rules_completions(
        ls,
        _complete_at_req(file_uri, cursor_pos),
    )
    # No completions (it has a space, so something funky is going on)
    assert not completions
