import re
from typing import (
    Union,
    Sequence,
    Optional,
    List,
)

from debputy.linting.lint_util import LintState
from debputy.lsp.debputy_ls import DebputyLanguageServer
from debputy.lsp.lsp_debian_control_reference_data import (
    Dep5FileMetadata,
)
from debputy.lsp.lsp_features import (
    lint_diagnostics,
    lsp_completer,
    lsp_hover,
    lsp_standard_handler,
    lsp_folding_ranges,
    lsp_semantic_tokens_full,
    lsp_will_save_wait_until,
    lsp_format_document,
    SecondaryLanguage,
    LanguageDispatchRule,
)
from debputy.lsp.lsp_generic_deb822 import (
    deb822_completer,
    deb822_hover,
    deb822_folding_ranges,
    deb822_semantic_tokens_full,
    deb822_format_file,
    scan_for_syntax_errors_and_token_level_diagnostics,
)
from debputy.lsp.vendoring._deb822_repro import (
    Deb822FileElement,
    Deb822ParagraphElement,
)
from debputy.lsprotocol.types import (
    CompletionItem,
    CompletionList,
    CompletionParams,
    HoverParams,
    Hover,
    TEXT_DOCUMENT_CODE_ACTION,
    SemanticTokens,
    SemanticTokensParams,
    FoldingRangeParams,
    FoldingRange,
    WillSaveTextDocumentParams,
    TextEdit,
    DocumentFormattingParams,
)

try:
    from debputy.lsp.vendoring._deb822_repro.locatable import (
        Position as TEPosition,
        Range as TERange,
    )

    from pygls.server import LanguageServer
    from pygls.workspace import TextDocument
except ImportError:
    pass


_CONTAINS_SPACE_OR_COLON = re.compile(r"[\s:]")

_DISPATCH_RULE = LanguageDispatchRule.new_rule(
    "debian/copyright",
    "debian/copyright",
    [
        # emacs's name
        SecondaryLanguage("debian-copyright"),
        # vim's name
        SecondaryLanguage("debcopyright"),
    ],
)

_DEP5_FILE_METADATA = Dep5FileMetadata()

lsp_standard_handler(_DISPATCH_RULE, TEXT_DOCUMENT_CODE_ACTION)


@lsp_hover(_DISPATCH_RULE)
def _debian_copyright_hover(
    ls: "DebputyLanguageServer",
    params: HoverParams,
) -> Optional[Hover]:
    return deb822_hover(ls, params, _DEP5_FILE_METADATA)


@lsp_completer(_DISPATCH_RULE)
def _debian_copyright_completions(
    ls: "DebputyLanguageServer",
    params: CompletionParams,
) -> Optional[Union[CompletionList, Sequence[CompletionItem]]]:
    return deb822_completer(ls, params, _DEP5_FILE_METADATA)


@lsp_folding_ranges(_DISPATCH_RULE)
def _debian_copyright_folding_ranges(
    ls: "DebputyLanguageServer",
    params: FoldingRangeParams,
) -> Optional[Sequence[FoldingRange]]:
    return deb822_folding_ranges(ls, params, _DEP5_FILE_METADATA)


def _looks_like_a_dep5_file(
    deb822_file: Deb822FileElement,
    stanzas: List[Deb822ParagraphElement],
) -> bool:
    if not stanzas or "Format" not in stanzas[0]:
        # No parseable stanzas or the first one did not have a Format, which is necessary.
        return False

    for part in deb822_file.iter_parts():
        if part.is_error:
            # Error first, then it might just be a "Format:" in the middle of a free-text file.
            return False
        if isinstance(part, Deb822ParagraphElement):
            break
    return True


@lint_diagnostics(_DISPATCH_RULE)
async def _lint_debian_copyright(lint_state: LintState) -> None:
    deb822_file = lint_state.parsed_deb822_file_content
    stanzas = list(deb822_file)

    if not _looks_like_a_dep5_file(deb822_file, stanzas):
        return

    first_error = await scan_for_syntax_errors_and_token_level_diagnostics(
        deb822_file,
        lint_state,
    )
    header_stanza, files_stanza, _ = _DEP5_FILE_METADATA.stanza_types()

    async for paragraph_no, paragraph in lint_state.slow_iter(
        enumerate(stanzas, start=1)
    ):
        paragraph_pos = paragraph.position_in_file()
        if paragraph_pos.line_position >= first_error:
            break
        is_files_or_license_stanza = paragraph_no != 1
        if is_files_or_license_stanza:
            stanza_metadata = _DEP5_FILE_METADATA.classify_stanza(
                paragraph,
                paragraph_no,
            )
            other_stanza_metadata = header_stanza
            other_stanza_name = "Header"
        elif "Format" in paragraph:
            stanza_metadata = header_stanza
            other_stanza_metadata = files_stanza
            other_stanza_name = "Files/License"
        else:
            break

        await stanza_metadata.stanza_diagnostics(
            deb822_file,
            paragraph,
            paragraph_pos,
            lint_state,
            confusable_with_stanza_name=other_stanza_name,
            confusable_with_stanza_metadata=other_stanza_metadata,
        )


@lsp_will_save_wait_until(_DISPATCH_RULE)
def _debian_copyright_on_save_formatting(
    ls: "DebputyLanguageServer",
    params: WillSaveTextDocumentParams,
) -> Optional[Sequence[TextEdit]]:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lint_state = ls.lint_state(doc)
    return deb822_format_file(lint_state, _DEP5_FILE_METADATA)


def _reformat_debian_copyright(
    lint_state: LintState,
) -> Optional[Sequence[TextEdit]]:
    return deb822_format_file(lint_state, _DEP5_FILE_METADATA)


@lsp_format_document(_DISPATCH_RULE)
def _debian_copyright_on_save_formatting(
    ls: "DebputyLanguageServer",
    params: DocumentFormattingParams,
) -> Optional[Sequence[TextEdit]]:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lint_state = ls.lint_state(doc)
    return deb822_format_file(lint_state, _DEP5_FILE_METADATA)


@lsp_semantic_tokens_full(_DISPATCH_RULE)
async def _debian_copyright_semantic_tokens_full(
    ls: "DebputyLanguageServer",
    request: SemanticTokensParams,
) -> Optional[SemanticTokens]:
    return await deb822_semantic_tokens_full(
        ls,
        request,
        _DEP5_FILE_METADATA,
    )
