import dataclasses
import importlib.resources
import os.path
import textwrap
from functools import lru_cache
from itertools import chain
from typing import (
    Union,
    Sequence,
    Tuple,
    Optional,
    Mapping,
    List,
    Iterable,
    Self,
    TYPE_CHECKING,
)

import debputy.lsp.data.deb822_data as deb822_ref_data_dir
from debputy.analysis.analysis_util import flatten_ppfs
from debputy.analysis.debian_dir import resolve_debhelper_config_files
from debputy.dh.dh_assistant import extract_dh_compat_level
from debputy.linting.lint_util import (
    LintState,
    te_range_to_lsp,
    te_position_to_lsp,
    with_range_in_continuous_parts,
)
from debputy.lsp.apt_cache import PackageLookup
from debputy.lsp.debputy_ls import DebputyLanguageServer
from debputy.lsp.lsp_debian_control_reference_data import (
    DctrlKnownField,
    DctrlFileMetadata,
    package_name_to_section,
    all_package_relationship_fields,
    extract_first_value_and_position,
    all_source_relationship_fields,
    StanzaMetadata,
    SUBSTVAR_RE,
)
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,
    lsp_text_doc_inlay_hints,
    LanguageDispatchRule,
    SecondaryLanguage,
    lsp_cli_reformat_document,
)
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.lsp_reference_keyword import LSP_DATA_DOMAIN
from debputy.lsp.quickfixes import (
    propose_correct_text_quick_fix,
    propose_insert_text_on_line_after_diagnostic_quick_fix,
    propose_remove_range_quick_fix,
)
from debputy.lsp.ref_models.deb822_reference_parse_models import (
    DCTRL_SUBSTVARS_REFERENCE_DATA_PARSER,
    DCtrlSubstvar,
)
from debputy.lsp.text_util import markdown_urlify
from debputy.lsp.vendoring._deb822_repro import (
    Deb822ParagraphElement,
)
from debputy.lsp.vendoring._deb822_repro.parsing import (
    Deb822KeyValuePairElement,
)
from debputy.lsprotocol.types import (
    Position,
    FoldingRange,
    FoldingRangeParams,
    CompletionItem,
    CompletionList,
    CompletionParams,
    HoverParams,
    Hover,
    TEXT_DOCUMENT_CODE_ACTION,
    SemanticTokens,
    SemanticTokensParams,
    WillSaveTextDocumentParams,
    TextEdit,
    DocumentFormattingParams,
    InlayHint,
)
from debputy.manifest_parser.util import AttributePath
from debputy.packager_provided_files import (
    PackagerProvidedFile,
    detect_all_packager_provided_files,
)
from debputy.plugin.api.impl import plugin_metadata_for_debputys_own_plugin
from debputy.util import PKGNAME_REGEX, _info, _trace_log, _is_trace_log_enabled
from debputy.yaml import MANIFEST_YAML

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

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

    from pygls.workspace import TextDocument
except ImportError:
    pass


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


@dataclasses.dataclass(slots=True, frozen=True)
class SubstvarMetadata:
    name: str
    defined_by: str
    dh_sequence: Optional[str]
    doc_uris: Sequence[str]
    synopsis: str
    description: str

    def render_metadata_fields(self) -> str:
        def_by = f"Defined by: {self.defined_by}"
        dh_seq = (
            f"DH Sequence: {self.dh_sequence}" if self.dh_sequence is not None else None
        )
        doc_uris = self.doc_uris
        parts = [def_by, dh_seq]
        if doc_uris:
            if len(doc_uris) == 1:
                parts.append(f"Documentation: {markdown_urlify(doc_uris[0])}")
            else:
                parts.append("Documentation:")
                parts.extend(f" - {markdown_urlify(uri)}" for uri in doc_uris)
        return "\n".join(parts)

    @classmethod
    def from_ref_data(cls, x: DCtrlSubstvar) -> "Self":
        doc = x.get("documentation", {})
        return cls(
            x["name"],
            x["defined_by"],
            x.get("dh_sequence"),
            doc.get("uris", []),
            doc.get("synopsis", ""),
            doc.get("long_description", ""),
        )


def relationship_substvar_for_field(substvar: str) -> Optional[str]:
    relationship_fields = all_package_relationship_fields()
    try:
        col_idx = substvar.rindex(":")
    except ValueError:
        return None
    return relationship_fields.get(substvar[col_idx + 1 : -1].lower())


def _as_substvars_metadata(
    args: List[SubstvarMetadata],
) -> Mapping[str, SubstvarMetadata]:
    r = {s.name: s for s in args}
    assert len(r) == len(args)
    return r


def dctrl_variables_metadata_basename() -> str:
    return "debian_control_variables_data.yaml"


@lru_cache
def dctrl_substvars_metadata() -> Mapping[str, SubstvarMetadata]:
    p = importlib.resources.files(deb822_ref_data_dir.__name__).joinpath(
        dctrl_variables_metadata_basename()
    )

    with p.open("r", encoding="utf-8") as fd:
        raw = MANIFEST_YAML.load(fd)

    attr_path = AttributePath.root_path(p)
    ref = DCTRL_SUBSTVARS_REFERENCE_DATA_PARSER.parse_input(raw, attr_path)
    return _as_substvars_metadata(
        [SubstvarMetadata.from_ref_data(x) for x in ref["variables"]]
    )


_DCTRL_FILE_METADATA = DctrlFileMetadata()


lsp_standard_handler(_DISPATCH_RULE, TEXT_DOCUMENT_CODE_ACTION)


@lsp_hover(_DISPATCH_RULE)
def _debian_control_hover(
    ls: "DebputyLanguageServer",
    params: HoverParams,
) -> Optional[Hover]:
    return deb822_hover(ls, params, _DCTRL_FILE_METADATA, custom_handler=_custom_hover)


def _custom_hover_description(
    _ls: "DebputyLanguageServer",
    _known_field: DctrlKnownField,
    line: str,
    _word_at_position: str,
) -> Optional[Union[Hover, str]]:
    if line[0].isspace():
        return None
    try:
        col_idx = line.index(":")
    except ValueError:
        return None

    content = line[col_idx + 1 :].strip()

    # Synopsis
    return textwrap.dedent(
        f"""\
        # Package synopsis

        The synopsis functions as a phrase describing the package, not a
        complete sentence, so sentential punctuation is inappropriate: it
        does not need extra capital letters or a final period (full stop).
        It should also omit any initial indefinite or definite article
        - "a", "an", or "the". Thus for instance:

        ```
        Package: libeg0
        Description: exemplification support library
        ```

        Technically this is a noun phrase minus articles, as opposed to a
        verb phrase. A good heuristic is that it should be possible to
        substitute the package name and synopsis into this formula:

        ```
        # Generic
        The package provides {{a,an,the,some}} synopsis.

        # The current package for comparison
        The package provides {{a,an,the,some}} {content}.
        ```

        Other advice for writing synopsis:
         * Avoid using the package name. Any software would display the
           package name already and it generally does not help the user
           understand what they are looking at.
         * In many situations, the user will only see the package name
           and its synopsis. The synopsis must be able to stand alone.

        **Example renderings in various terminal UIs**:
        ```
        # apt search TERM
        package/stable,now 1.0-1 all:
           {content}

        # apt-get search TERM
        package - {content}
        ```

        ## Reference example

        An reference example for comparison: The Sphinx package
        (python3-sphinx/7.2.6-6) had the following synopsis:

        ```
        Description: documentation generator for Python projects
        ```

        In the test sentence, it would read as:

        ```
        The python3-sphinx package provides a documentation generator for Python projects.
        ```

        **Side-by-side comparison in the terminal UIs**:
        ```
        # apt search TERM
        python3-sphinx/stable,now 7.2.6-6 all:
           documentation generator for Python projects

        package/stable,now 1.0-1 all:
           {content}


        # apt-get search TERM
        package - {content}
        python3-sphinx - documentation generator for Python projects
        ```
    """
    )


def _render_package_lookup(
    package_lookup: PackageLookup,
    known_field: DctrlKnownField,
) -> str:
    name = package_lookup.name
    provider = package_lookup.package
    if package_lookup.package is None and len(package_lookup.provided_by) == 1:
        provider = package_lookup.provided_by[0]

    if provider:
        segments = [
            f"# {name} ({provider.version}, {provider.architecture}) ",
            "",
        ]

        if (
            _is_bd_field(known_field)
            and name.startswith("dh-sequence-")
            and len(name) > 12
        ):
            sequence = name[12:]
            segments.append(
                f"This build-dependency will activate the `dh` sequence called `{sequence}`."
            )
            segments.append("")

        elif (
            known_field.name == "Build-Depends"
            and name.startswith("debputy-plugin-")
            and len(name) > 15
        ):
            plugin_name = name[15:]
            segments.append(
                f"This build-dependency will activate the `debputy` plugin called `{plugin_name}`."
            )
            segments.append("")

        segments.extend(
            [
                f"Synopsis: {provider.synopsis}",
                "",
                f"Multi-Arch: {provider.multi_arch}",
                "",
                f"Section: {provider.section}",
            ]
        )
        if provider.upstream_homepage is not None:
            segments.append("")
            segments.append(f"Upstream homepage: {provider.upstream_homepage}")
        segments.append("")
        segments.append(
            "Data is from the system's APT cache, which may not match the target distribution."
        )
        return "\n".join(segments)

    segments = [
        f"# {name} [virtual]",
        "",
        "The package {name} is a virtual package provided by one of:",
    ]
    segments.extend(f" * {p.name}" for p in package_lookup.provided_by)
    segments.append("")
    segments.append(
        "Data is from the system's APT cache, which may not match the target distribution."
    )
    return "\n".join(segments)


def _disclaimer(is_empty: bool) -> str:
    if is_empty:
        return textwrap.dedent(
            """\
        The system's APT cache is empty, so it was not possible to verify that the
        package exist.
"""
        )
    return textwrap.dedent(
        """\
        The package is not known by the APT cache on this system, so there may be typo
        or the package may not be available in the version of your distribution.
"""
    )


def _render_package_by_name(
    name: str, known_field: DctrlKnownField, is_empty: bool
) -> Optional[str]:
    if _is_bd_field(known_field) and name.startswith("dh-sequence-") and len(name) > 12:
        sequence = name[12:]
        return (
            textwrap.dedent(
                f"""\
        # {name}

        This build-dependency will activate the `dh` sequence called `{sequence}`.

        """
            )
            + _disclaimer(is_empty)
        )
    if (
        known_field.name == "Build-Depends"
        and name.startswith("debputy-plugin-")
        and len(name) > 15
    ):
        plugin_name = name[15:]
        return (
            textwrap.dedent(
                f"""\
        # {name}

        This build-dependency will activate the `debputy` plugin called `{plugin_name}`.

        """
            )
            + _disclaimer(is_empty)
        )
    return (
        textwrap.dedent(
            f"""\
        # {name}

    """
        )
        + _disclaimer(is_empty)
    )


def _is_bd_field(known_field: DctrlKnownField) -> bool:
    return known_field.name in (
        "Build-Depends",
        "Build-Depends-Arch",
        "Build-Depends-Indep",
    )


def _custom_hover_relationship_field(
    ls: "DebputyLanguageServer",
    known_field: DctrlKnownField,
    _line: str,
    word_at_position: str,
) -> Optional[Union[Hover, str]]:
    apt_cache = ls.apt_cache
    state = apt_cache.state
    is_empty = False
    _info(f"Rel field: {known_field.name} - {word_at_position} - {state}")
    if "|" in word_at_position:
        return textwrap.dedent(
            f"""\
            Sorry, no hover docs for OR relations at the moment.

            The relation being matched: `{word_at_position}`

            The code is missing logic to determine which side of the OR the lookup is happening.
        """
        )
    match = next(iter(PKGNAME_REGEX.finditer(word_at_position)), None)
    if match is None:
        return
    package = match.group()
    if state == "empty-cache":
        state = "loaded"
        is_empty = True
    if state == "loaded":
        result = apt_cache.lookup(package)
        if result is None:
            return _render_package_by_name(
                package,
                known_field,
                is_empty=is_empty,
            )
        return _render_package_lookup(result, known_field)

    if state in (
        "not-loaded",
        "failed",
        "tooling-not-available",
    ):
        details = apt_cache.load_error if apt_cache.load_error else "N/A"
        return textwrap.dedent(
            f"""\
        Sorry, the APT cache data is not available due to an error or missing tool.

        Details: {details}
        """
        )

    if state == "empty-cache":
        return f"Cannot lookup {package}: APT cache data was empty"

    if state == "loading":
        return f"Cannot lookup {package}: APT cache data is still being indexed. Please try again in a moment."
    return None


_CUSTOM_FIELD_HOVER = {
    field: _custom_hover_relationship_field
    for field in chain(
        all_package_relationship_fields().values(),
        all_source_relationship_fields().values(),
    )
    if field != "Provides"
}

_CUSTOM_FIELD_HOVER["Description"] = _custom_hover_description


def _custom_hover(
    ls: "DebputyLanguageServer",
    server_position: Position,
    _current_field: Optional[str],
    word_at_position: str,
    known_field: Optional[DctrlKnownField],
    in_value: bool,
    _doc: "TextDocument",
    lines: List[str],
) -> Optional[Union[Hover, str]]:
    if not in_value:
        return None

    line_no = server_position.line
    line = lines[line_no]
    substvar_search_ref = server_position.character
    substvar = ""
    try:
        if line and line[substvar_search_ref] in ("$", "{"):
            substvar_search_ref += 2
        substvar_start = line.rindex("${", 0, substvar_search_ref)
        substvar_end = line.index("}", substvar_start)
        if server_position.character <= substvar_end:
            substvar = line[substvar_start : substvar_end + 1]
    except (ValueError, IndexError):
        pass

    if substvar == "${}" or SUBSTVAR_RE.fullmatch(substvar):
        substvar_md = dctrl_substvars_metadata().get(substvar)

        computed_doc = ""
        for_field = relationship_substvar_for_field(substvar)
        if for_field:
            # Leading empty line is intentional!
            computed_doc = textwrap.dedent(
                f"""
                This substvar is a relationship substvar for the field {for_field}.
                Relationship substvars are automatically added in the field they
                are named after in `debhelper-compat (= 14)` or later, or with
                `debputy` (any integration mode after 0.1.21).
            """
            )

        if substvar_md is None:
            doc = f"No documentation for {substvar}.\n"
            md_fields = ""
        else:
            doc = ls.translation(LSP_DATA_DOMAIN).pgettext(
                f"Variable:{substvar_md.name}",
                substvar_md.description,
            )
            md_fields = "\n" + substvar_md.render_metadata_fields()
        return f"# Substvar `{substvar}`\n\n{doc}{computed_doc}{md_fields}"

    if known_field is None:
        return None
    dispatch = _CUSTOM_FIELD_HOVER.get(known_field.name)
    if dispatch is None:
        return None
    return dispatch(ls, known_field, line, word_at_position)


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


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


@lsp_text_doc_inlay_hints(_DISPATCH_RULE)
async def _doc_inlay_hint(
    ls: "DebputyLanguageServer",
    params: types.InlayHintParams,
) -> Optional[List[InlayHint]]:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lint_state = ls.lint_state(doc)
    deb822_file = lint_state.parsed_deb822_file_content
    if not deb822_file:
        return None
    inlay_hints = []
    stanzas = list(deb822_file)
    if len(stanzas) < 2:
        return None
    source_stanza = stanzas[0]
    source_stanza_pos = source_stanza.position_in_file()
    inherited_inlay_label_part = {}
    stanza_no = 0

    async for stanza_range, stanza in lint_state.slow_iter(
        with_range_in_continuous_parts(deb822_file.iter_parts())
    ):
        if not isinstance(stanza, Deb822ParagraphElement):
            continue
        stanza_def = _DCTRL_FILE_METADATA.classify_stanza(stanza, stanza_no)
        stanza_no += 1
        pkg_kvpair = stanza.get_kvpair_element(("Package", 0), use_get=True)
        if pkg_kvpair is None:
            continue

        parts = []
        async for known_field in ls.slow_iter(
            stanza_def.stanza_fields.values(), yield_every=25
        ):
            if (
                not known_field.inheritable_from_other_stanza
                or not known_field.show_as_inherited
                or known_field.name in stanza
            ):
                continue

            inherited_value = source_stanza.get(known_field.name)
            if inherited_value is not None:
                inlay_hint_label_part = inherited_inlay_label_part.get(known_field.name)
                if inlay_hint_label_part is None:
                    kvpair = source_stanza.get_kvpair_element(known_field.name)
                    value_range_te = kvpair.range_in_parent().relative_to(
                        source_stanza_pos
                    )
                    value_range = doc.position_codec.range_to_client_units(
                        lint_state.lines,
                        te_range_to_lsp(value_range_te),
                    )
                    inlay_hint_label_part = types.InlayHintLabelPart(
                        f"  ({known_field.name}: {inherited_value})",
                        tooltip="Inherited from Source stanza",
                        location=types.Location(
                            params.text_document.uri,
                            value_range,
                        ),
                    )
                    inherited_inlay_label_part[known_field.name] = inlay_hint_label_part
                parts.append(inlay_hint_label_part)

        if parts:
            known_field = stanza_def["Package"]
            values = known_field.field_value_class.interpreter().interpret(pkg_kvpair)
            assert values is not None
            anchor_value = list(values.iter_value_references())[-1]
            anchor_position = (
                anchor_value.locatable.range_in_parent().end_pos.relative_to(
                    pkg_kvpair.value_element.position_in_parent().relative_to(
                        stanza_range.start_pos
                    )
                )
            )
            anchor_position_client_units = doc.position_codec.position_to_client_units(
                lint_state.lines,
                te_position_to_lsp(anchor_position),
            )
            inlay_hints.append(
                types.InlayHint(
                    anchor_position_client_units,
                    parts,
                    padding_left=True,
                    padding_right=False,
                )
            )
    return inlay_hints


def _source_package_checks(
    stanza: Deb822ParagraphElement,
    stanza_position: "TEPosition",
    stanza_metadata: StanzaMetadata[DctrlKnownField],
    lint_state: LintState,
) -> None:
    vcs_fields = {}
    source_fields = _DCTRL_FILE_METADATA["Source"].stanza_fields
    for kvpair in stanza.iter_parts_of_type(Deb822KeyValuePairElement):
        name = stanza_metadata.normalize_field_name(kvpair.field_name.lower())
        if (
            not name.startswith("vcs-")
            or name == "vcs-browser"
            or name not in source_fields
        ):
            continue
        vcs_fields[name] = kvpair

    if len(vcs_fields) < 2:
        return
    for kvpair in vcs_fields.values():
        lint_state.emit_diagnostic(
            kvpair.range_in_parent().relative_to(stanza_position),
            f'Multiple Version Control fields defined ("{kvpair.field_name}")',
            "warning",
            "Policy 5.6.26",
            quickfixes=[
                propose_remove_range_quick_fix(
                    proposed_title=f'Remove "{kvpair.field_name}"'
                )
            ],
        )


def _binary_package_checks(
    stanza: Deb822ParagraphElement,
    stanza_position: "TEPosition",
    source_stanza: Deb822ParagraphElement,
    representation_field_range: "TERange",
    lint_state: LintState,
) -> None:
    package_name = stanza.get("Package", "")
    source_section = source_stanza.get("Section")
    section_kvpair = stanza.get_kvpair_element(("Section", 0), use_get=True)
    section: Optional[str] = None
    section_range: Optional["TERange"] = None
    if section_kvpair is not None:
        section, section_range = extract_first_value_and_position(
            section_kvpair,
            stanza_position,
        )

    if section_range is None:
        section_range = representation_field_range
    effective_section = section or source_section or "unknown"
    package_type = stanza.get("Package-Type", "")
    component_prefix = ""
    if "/" in effective_section:
        component_prefix, effective_section = effective_section.split("/", maxsplit=1)
        component_prefix += "/"

    if package_name.endswith("-udeb") or package_type == "udeb":
        if package_type != "udeb":
            package_type_kvpair = stanza.get_kvpair_element(
                "Package-Type", use_get=True
            )
            package_type_range: Optional["TERange"] = None
            if package_type_kvpair is not None:
                _, package_type_range = extract_first_value_and_position(
                    package_type_kvpair,
                    stanza_position,
                )
            if package_type_range is None:
                package_type_range = representation_field_range
            lint_state.emit_diagnostic(
                package_type_range,
                'The Package-Type should be "udeb" given the package name',
                "warning",
                "debputy",
            )
        guessed_section = "debian-installer"
        section_diagnostic_rationale = " since it is an udeb"
    else:
        guessed_section = package_name_to_section(package_name)
        section_diagnostic_rationale = " based on the package name"
    if guessed_section is not None and guessed_section != effective_section:
        if section is not None:
            quickfix_data = [
                propose_correct_text_quick_fix(f"{component_prefix}{guessed_section}")
            ]
        else:
            quickfix_data = [
                propose_insert_text_on_line_after_diagnostic_quick_fix(
                    f"Section: {component_prefix}{guessed_section}\n"
                )
            ]
        assert section_range is not None  # mypy hint
        lint_state.emit_diagnostic(
            section_range,
            f'The Section should be "{component_prefix}{guessed_section}"{section_diagnostic_rationale}',
            "warning",
            "debputy",
            quickfixes=quickfix_data,
        )


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

    if not _DCTRL_FILE_METADATA.file_metadata_applies_to_file(deb822_file):
        return

    first_error = await scan_for_syntax_errors_and_token_level_diagnostics(
        deb822_file,
        lint_state,
    )

    stanzas = list(deb822_file)
    source_stanza = stanzas[0] if stanzas else None
    binary_stanzas_w_pos = []

    source_stanza_metadata, binary_stanza_metadata = _DCTRL_FILE_METADATA.stanza_types()
    stanza_no = 0

    async for stanza_range, stanza in lint_state.slow_iter(
        with_range_in_continuous_parts(deb822_file.iter_parts())
    ):
        if not isinstance(stanza, Deb822ParagraphElement):
            continue
        stanza_position = stanza_range.start_pos
        if stanza_position.line_position >= first_error:
            break
        stanza_no += 1
        is_binary_stanza = stanza_no != 1
        if is_binary_stanza:
            stanza_metadata = binary_stanza_metadata
            other_stanza_metadata = source_stanza_metadata
            other_stanza_name = "Source"
            binary_stanzas_w_pos.append((stanza, stanza_position))
            _, representation_field_range = stanza_metadata.stanza_representation(
                stanza, stanza_position
            )
            _binary_package_checks(
                stanza,
                stanza_position,
                source_stanza,
                representation_field_range,
                lint_state,
            )
        else:
            stanza_metadata = source_stanza_metadata
            other_stanza_metadata = binary_stanza_metadata
            other_stanza_name = "Binary"
            _source_package_checks(
                stanza,
                stanza_position,
                stanza_metadata,
                lint_state,
            )

        await stanza_metadata.stanza_diagnostics(
            deb822_file,
            stanza,
            stanza_position,
            lint_state,
            confusable_with_stanza_metadata=other_stanza_metadata,
            confusable_with_stanza_name=other_stanza_name,
            inherit_from_stanza=source_stanza if is_binary_stanza else None,
        )

    _detect_misspelled_packaging_files(
        lint_state,
        binary_stanzas_w_pos,
    )


def _package_range_of_stanza(
    binary_stanzas: List[Tuple[Deb822ParagraphElement, TEPosition]],
) -> Iterable[Tuple[str, Optional[str], "TERange"]]:
    for stanza, stanza_position in binary_stanzas:
        kvpair = stanza.get_kvpair_element(("Package", 0), use_get=True)
        if kvpair is None:
            continue
        representation_field_range = kvpair.range_in_parent().relative_to(
            stanza_position
        )
        yield stanza["Package"], stanza.get("Architecture"), representation_field_range


def _packaging_files(
    lint_state: LintState,
) -> Iterable[PackagerProvidedFile]:
    source_root = lint_state.source_root
    debian_dir = lint_state.debian_dir
    binary_packages = lint_state.binary_packages
    if (
        source_root is None
        or not source_root.has_fs_path
        or debian_dir is None
        or binary_packages is None
    ):
        return

    debputy_integration_mode = lint_state.debputy_metadata.debputy_integration_mode
    dh_sequencer_data = lint_state.dh_sequencer_data
    dh_sequences = dh_sequencer_data.sequences
    is_debputy_package = debputy_integration_mode is not None
    feature_set = lint_state.plugin_feature_set
    known_packaging_files = feature_set.known_packaging_files
    static_packaging_files = {
        kpf.detection_value: kpf
        for kpf in known_packaging_files.values()
        if kpf.detection_method == "path"
    }
    ignored_path = set(static_packaging_files)

    if is_debputy_package:
        all_debputy_ppfs = list(
            flatten_ppfs(
                detect_all_packager_provided_files(
                    feature_set,
                    debian_dir,
                    binary_packages,
                    allow_fuzzy_matches=True,
                    detect_typos=True,
                    ignore_paths=ignored_path,
                )
            )
        )
        for ppf in all_debputy_ppfs:
            if ppf.path.path in ignored_path:
                continue
            ignored_path.add(ppf.path.path)
            yield ppf

    # FIXME: This should read the editor data, but dh_assistant does not support that.
    dh_compat_level, _ = extract_dh_compat_level(cwd=source_root.fs_path)
    if dh_compat_level is not None:
        debputy_plugin_metadata = plugin_metadata_for_debputys_own_plugin()
        (
            all_dh_ppfs,
            _,
            _,
            _,
        ) = resolve_debhelper_config_files(
            debian_dir,
            binary_packages,
            debputy_plugin_metadata,
            feature_set,
            dh_sequences,
            dh_compat_level,
            saw_dh=dh_sequencer_data.uses_dh_sequencer,
            ignore_paths=ignored_path,
            debputy_integration_mode=debputy_integration_mode,
            cwd=source_root.fs_path,
        )
        for ppf in all_dh_ppfs:
            if ppf.path.path in ignored_path:
                continue
            ignored_path.add(ppf.path.path)
            yield ppf


def _detect_misspelled_packaging_files(
    lint_state: LintState,
    binary_stanzas_w_pos: List[Tuple[Deb822ParagraphElement, TEPosition]],
) -> None:
    stanza_ranges = {
        p: (a, r) for p, a, r in _package_range_of_stanza(binary_stanzas_w_pos)
    }
    for ppf in _packaging_files(lint_state):
        binary_package = ppf.package_name
        explicit_package = ppf.uses_explicit_package_name
        name_segment = ppf.name_segment is not None
        stem = ppf.definition.stem
        if _is_trace_log_enabled():
            _trace_log(
                f"PPF check: {binary_package} {stem=} {explicit_package=} {name_segment=} {ppf.expected_path=} {ppf.definition.has_active_command=}"
            )
        if binary_package is None or stem is None:
            continue
        res = stanza_ranges.get(binary_package)
        if res is None:
            continue
        declared_arch, diag_range = res
        if diag_range is None:
            continue
        path = ppf.path.path
        likely_typo_of = ppf.expected_path
        arch_restriction = ppf.architecture_restriction
        if likely_typo_of is not None:
            # Handles arch_restriction == 'all' at the same time due to how
            # the `likely-typo-of` is created
            lint_state.emit_diagnostic(
                diag_range,
                f'The file "{path}" is likely a typo of "{likely_typo_of}"',
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )
            continue
        if declared_arch == "all" and arch_restriction is not None:
            lint_state.emit_diagnostic(
                diag_range,
                f'The file "{path}" has an architecture restriction but is for an `arch:all` package, so'
                f" the restriction does not make sense.",
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )
        elif arch_restriction == "all":
            lint_state.emit_diagnostic(
                diag_range,
                f'The file "{path}" has an architecture restriction of `all` rather than a real architecture',
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )

        if not ppf.definition.has_active_command:
            lint_state.emit_diagnostic(
                diag_range,
                f"The file {path} is related to a command that is not active in the dh sequence"
                " with the current addons",
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )
            continue

        if not explicit_package and name_segment is not None:
            basename = os.path.basename(path)
            if basename == ppf.definition.stem:
                continue
            alt_name = f"{binary_package}.{stem}"
            if arch_restriction is not None:
                alt_name = f"{alt_name}.{arch_restriction}"
            if ppf.definition.allow_name_segment:
                or_alt_name = f' (or maybe "debian/{binary_package}.{basename}")'
            else:
                or_alt_name = ""

            lint_state.emit_diagnostic(
                diag_range,
                f'Possible typo in "{path}". Consider renaming the file to "debian/{alt_name}"'
                f"{or_alt_name} if it is intended for {binary_package}",
                "warning",
                "debputy",
                diagnostic_applies_to_another_file=path,
            )


@lsp_will_save_wait_until(_DISPATCH_RULE)
def _debian_control_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 _reformat_debian_control(lint_state)


@lsp_cli_reformat_document(_DISPATCH_RULE)
def _reformat_debian_control(
    lint_state: LintState,
) -> Optional[Sequence[TextEdit]]:
    return deb822_format_file(lint_state, _DCTRL_FILE_METADATA)


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


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