from typing import (
    Optional,
    Any,
    Tuple,
    Union,
    Sequence,
    Literal,
    get_args,
    get_origin,
    Container,
)

from debputy.highlevel_manifest import MANIFEST_YAML
from debputy.linting.lint_util import LintState
from debputy.lsp.lsp_features import (
    lint_diagnostics,
    lsp_standard_handler,
    lsp_hover,
    lsp_completer,
    SecondaryLanguage,
    LanguageDispatchRule,
)
from debputy.lsp.lsp_generic_yaml import (
    word_range_at_position,
    YAML_COMPLETION_HINT_KEY,
    insert_complete_marker_snippet,
    yaml_key_range,
    yaml_flag_unknown_key,
    _trace_cursor,
    generic_yaml_hover,
    resolve_keyword,
    DEBPUTY_PLUGIN_METADATA,
    maybe_quote_yaml_value,
    completion_from_attr,
)
from debputy.lsp.quickfixes import propose_correct_text_quick_fix
from debputy.lsp.vendoring._deb822_repro.locatable import (
    Position as TEPosition,
    Range as TERange,
)
from debputy.lsprotocol.types import (
    TEXT_DOCUMENT_WILL_SAVE_WAIT_UNTIL,
    HoverParams,
    Hover,
    TEXT_DOCUMENT_CODE_ACTION,
    CompletionParams,
    CompletionList,
    CompletionItem,
    DiagnosticRelatedInformation,
    Location,
)
from debputy.manifest_parser.declarative_parser import (
    AttributeDescription,
    ParserGenerator,
    DeclarativeNonMappingInputParser,
)
from debputy.manifest_parser.declarative_parser import DeclarativeMappingInputParser
from debputy.manifest_parser.tagging_types import DebputyDispatchableType
from debputy.manifest_parser.util import AttributePath
from debputy.plugin.api.impl_types import (
    DeclarativeInputParser,
    DispatchingParserBase,
    ListWrappedDeclarativeInputParser,
    InPackageContextParser,
    DeclarativeValuelessKeywordInputParser,
)
from debputy.plugin.api.parser_tables import OPARSER_MANIFEST_ROOT
from debputy.plugin.api.spec import DebputyIntegrationMode
from debputy.plugin.debputy.private_api import Capability, load_libcap
from debputy.util import _info
from debputy.yaml.compat import (
    CommentedMap,
    CommentedSeq,
    MarkedYAMLError,
    YAMLError,
)

try:
    from pygls.server import LanguageServer
    from debputy.lsp.debputy_ls import DebputyLanguageServer
except ImportError:
    pass


_DISPATCH_RULE = LanguageDispatchRule.new_rule(
    "debian/debputy.manifest",
    "debian/debputy.manifest",
    [
        SecondaryLanguage("debputy.manifest"),
        # LSP's official language ID for YAML files
        SecondaryLanguage("yaml", filename_based_lookup=True),
    ],
)


lsp_standard_handler(_DISPATCH_RULE, TEXT_DOCUMENT_CODE_ACTION)
lsp_standard_handler(_DISPATCH_RULE, TEXT_DOCUMENT_WILL_SAVE_WAIT_UNTIL)


@lint_diagnostics(_DISPATCH_RULE)
def _lint_debian_debputy_manifest(lint_state: LintState) -> None:
    lines = lint_state.lines
    try:
        content = MANIFEST_YAML.load("".join(lines))
    except MarkedYAMLError as e:
        if e.context_mark:
            line = e.context_mark.line
            column = e.context_mark.column + 1
        else:
            line = e.problem_mark.line
            column = e.problem_mark.column + 1
        error_range = word_range_at_position(
            lines,
            line,
            column,
        )
        lint_state.emit_diagnostic(
            error_range, f"YAML parse error: {e}", "error", "debputy"
        )
    except YAMLError as e:
        error_range = TERange(
            TEPosition(0, 0),
            TEPosition(0, len(lines[0])),
        )
        lint_state.emit_diagnostic(
            error_range,
            f"Unknown YAML parse error: {e} [{e!r}]",
            "error",
            "debputy",
        )
    else:
        feature_set = lint_state.plugin_feature_set
        pg = feature_set.manifest_parser_generator
        root_parser = pg.dispatchable_object_parsers[OPARSER_MANIFEST_ROOT]
        debputy_integration_mode = lint_state.debputy_metadata.debputy_integration_mode

        _lint_content(
            lint_state,
            pg,
            root_parser,
            debputy_integration_mode,
            content,
        )


def _integration_mode_allows_key(
    lint_state: LintState,
    debputy_integration_mode: Optional[DebputyIntegrationMode],
    expected_debputy_integration_modes: Optional[Container[DebputyIntegrationMode]],
    key: str,
    line: int,
    col: int,
) -> None:
    if debputy_integration_mode is None or expected_debputy_integration_modes is None:
        return
    if debputy_integration_mode in expected_debputy_integration_modes:
        return
    key_range = yaml_key_range(key, line, col)
    lint_state.emit_diagnostic(
        key_range,
        f'Feature "{key}" not supported in integration mode {debputy_integration_mode}',
        "error",
        "debputy",
    )


def _conflicting_key(
    lint_state: LintState,
    key_a: str,
    key_b: str,
    key_a_line: int,
    key_a_col: int,
    key_b_line: int,
    key_b_col: int,
) -> None:
    key_a_range = TERange(
        TEPosition(
            key_a_line,
            key_a_col,
        ),
        TEPosition(
            key_a_line,
            key_a_col + len(key_a),
        ),
    )
    key_b_range = TERange(
        TEPosition(
            key_b_line,
            key_b_col,
        ),
        TEPosition(
            key_b_line,
            key_b_col + len(key_b),
        ),
    )
    lint_state.emit_diagnostic(
        key_a_range,
        f'The "{key_a}" cannot be used with "{key_b}".',
        "error",
        "debputy",
        related_information=[
            DiagnosticRelatedInformation(
                location=Location(
                    lint_state.doc_uri,
                    key_b_range,
                ),
                message=f'The attribute "{key_b}" is used here.',
            )
        ],
    )

    lint_state.emit_diagnostic(
        key_b_range,
        f'The "{key_b}" cannot be used with "{key_a}".',
        "error",
        "debputy",
        related_information=[
            DiagnosticRelatedInformation(
                location=Location(
                    lint_state.doc_uri,
                    key_a_range,
                ),
                message=f'The attribute "{key_a}" is used here.',
            )
        ],
    )


def _remaining_line(lint_state: LintState, line_no: int, pos_start: int) -> "TERange":
    raw_line = lint_state.lines[line_no].rstrip()
    pos_end = len(raw_line)
    return TERange(
        TEPosition(
            line_no,
            pos_start,
        ),
        TEPosition(
            line_no,
            pos_end,
        ),
    )


def _lint_attr_value(
    lint_state: LintState,
    attr: AttributeDescription,
    pg: ParserGenerator,
    debputy_integration_mode: Optional[DebputyIntegrationMode],
    key: str,
    value: Any,
    pos: Tuple[int, int],
) -> None:
    target_attr_type = attr.attribute_type
    type_mapping = pg.get_mapped_type_from_target_type(target_attr_type)
    source_attr_type = target_attr_type
    if type_mapping is not None:
        source_attr_type = type_mapping.source_type
    orig = get_origin(source_attr_type)
    valid_values: Optional[Sequence[Any]] = None
    if orig == Literal:
        valid_values = get_args(attr.attribute_type)
    elif orig == bool or attr.attribute_type == bool:
        valid_values = (True, False)
    elif isinstance(target_attr_type, type):
        if issubclass(target_attr_type, Capability):
            has_libcap, _, is_valid_cap = load_libcap()
            if has_libcap and not is_valid_cap(value):
                line_no, cursor_pos = pos
                cap_range = _remaining_line(lint_state, line_no, cursor_pos)
                lint_state.emit_diagnostic(
                    cap_range,
                    "The value could not be parsed as a capability via cap_from_text on this system",
                    "warning",
                    "debputy",
                )
            return
        if issubclass(target_attr_type, DebputyDispatchableType):
            parser = pg.dispatch_parser_table_for(target_attr_type)
            _lint_content(
                lint_state,
                pg,
                parser,
                debputy_integration_mode,
                value,
            )
            return

    if valid_values is None or value in valid_values:
        return
    line_no, cursor_pos = pos
    value_range = _remaining_line(lint_state, line_no, cursor_pos)
    lint_state.emit_diagnostic(
        value_range,
        f'Not a supported value for "{key}"',
        "error",
        "debputy",
        quickfixes=[
            propose_correct_text_quick_fix(_as_yaml_value(m)) for m in valid_values
        ],
    )


def _as_yaml_value(v: Any) -> str:
    if isinstance(v, bool):
        return str(v).lower()
    return str(v)


def _lint_declarative_mapping_input_parser(
    lint_state: LintState,
    pg: ParserGenerator,
    parser: DeclarativeMappingInputParser,
    debputy_integration_mode: Optional[DebputyIntegrationMode],
    content: Any,
) -> None:
    if not isinstance(content, CommentedMap):
        return
    lc = content.lc
    for key, value in content.items():
        attr = parser.manifest_attributes.get(key)
        line, col = lc.key(key)
        if attr is None:
            corrected_key = yaml_flag_unknown_key(
                lint_state,
                key,
                parser.manifest_attributes,
                line,
                col,
            )
            if corrected_key:
                key = corrected_key
                attr = parser.manifest_attributes.get(corrected_key)
        if attr is None:
            continue

        _lint_attr_value(
            lint_state,
            attr,
            pg,
            debputy_integration_mode,
            key,
            value,
            lc.value(key),
        )

        for forbidden_key in attr.conflicting_attributes:
            if forbidden_key in content:
                con_line, con_col = lc.key(forbidden_key)
                _conflicting_key(
                    lint_state,
                    key,
                    forbidden_key,
                    line,
                    col,
                    con_line,
                    con_col,
                )
    for mx in parser.mutually_exclusive_attributes:
        matches = content.keys() & mx
        if len(matches) < 2:
            continue
        key, *others = list(matches)
        line, col = lc.key(key)
        for other in others:
            con_line, con_col = lc.key(other)
            _conflicting_key(
                lint_state,
                key,
                other,
                line,
                col,
                con_line,
                con_col,
            )


def _lint_content(
    lint_state: LintState,
    pg: ParserGenerator,
    parser: DeclarativeInputParser[Any],
    debputy_integration_mode: Optional[DebputyIntegrationMode],
    content: Any,
) -> None:
    if isinstance(parser, DispatchingParserBase):
        if not isinstance(content, CommentedMap):
            return
        lc = content.lc
        for key, value in content.items():
            is_known = parser.is_known_keyword(key)
            line, col = lc.key(key)
            orig_key = key
            if not is_known:
                corrected_key = yaml_flag_unknown_key(
                    lint_state,
                    key,
                    parser.registered_keywords(),
                    line,
                    col,
                    unknown_keys_diagnostic_severity=parser.unknown_keys_diagnostic_severity,
                )
                if corrected_key is not None:
                    key = corrected_key
                    is_known = True

            if is_known:
                subparser = parser.parser_for(key)
                assert subparser is not None
                _integration_mode_allows_key(
                    lint_state,
                    debputy_integration_mode,
                    subparser.parser.expected_debputy_integration_mode,
                    orig_key,
                    line,
                    col,
                )
                _lint_content(
                    lint_state,
                    pg,
                    subparser.parser,
                    debputy_integration_mode,
                    value,
                )
    elif isinstance(parser, ListWrappedDeclarativeInputParser):
        if not isinstance(content, CommentedSeq):
            return
        subparser = parser.delegate
        for value in content:
            _lint_content(lint_state, pg, subparser, debputy_integration_mode, value)
    elif isinstance(parser, InPackageContextParser):
        if not isinstance(content, CommentedMap):
            return
        known_packages = lint_state.binary_packages
        lc = content.lc
        for k, v in content.items():
            if "{{" not in k and known_packages is not None and k not in known_packages:
                line, col = lc.key(k)
                yaml_flag_unknown_key(
                    lint_state,
                    k,
                    known_packages,
                    line,
                    col,
                    message_format='Unknown package "{key}".',
                )
            _lint_content(
                lint_state,
                pg,
                parser.delegate,
                debputy_integration_mode,
                v,
            )
    elif isinstance(parser, DeclarativeMappingInputParser):
        _lint_declarative_mapping_input_parser(
            lint_state,
            pg,
            parser,
            debputy_integration_mode,
            content,
        )


@lsp_completer(_DISPATCH_RULE)
def debputy_manifest_completer(
    ls: "DebputyLanguageServer",
    params: CompletionParams,
) -> Optional[Union[CompletionList, Sequence[CompletionItem]]]:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lines = doc.lines
    server_position = doc.position_codec.position_from_client_units(
        lines, params.position
    )
    orig_line = lines[server_position.line].rstrip()
    has_colon = ":" in orig_line
    added_key = insert_complete_marker_snippet(lines, server_position)
    attempts = 1 if added_key else 2
    content = None

    while attempts > 0:
        attempts -= 1
        try:
            content = MANIFEST_YAML.load("".join(lines))
            break
        except MarkedYAMLError as e:
            context_line = (
                e.context_mark.line if e.context_mark else e.problem_mark.line
            )
            if (
                e.problem_mark.line != server_position.line
                and context_line != server_position.line
            ):
                l_data = (
                    lines[e.problem_mark.line].rstrip()
                    if e.problem_mark.line < len(lines)
                    else "N/A (OOB)"
                )

                _info(f"Parse error on line: {e.problem_mark.line}: {l_data}")
                return None

            if attempts > 0:
                # Try to make it a key and see if that fixes the problem
                new_line = (
                    lines[server_position.line].rstrip() + YAML_COMPLETION_HINT_KEY
                )
                lines[server_position.line] = new_line
        except YAMLError:
            break
    if content is None:
        context = lines[server_position.line].replace("\n", "\\n")
        _info(f"Completion failed: parse error: Line in question: {context}")
        return None
    attribute_root_path = AttributePath.root_path(content)
    m = _trace_cursor(content, attribute_root_path, server_position)

    if m is None:
        _info("No match")
        return None
    matched_key, attr_path, matched, parent = m
    _info(f"Matched path: {matched} (path: {attr_path.path}) [{matched_key=}]")
    feature_set = ls.plugin_feature_set
    root_parser = feature_set.manifest_parser_generator.dispatchable_object_parsers[
        OPARSER_MANIFEST_ROOT
    ]
    segments = list(attr_path.path_segments())
    km = resolve_keyword(
        root_parser,
        DEBPUTY_PLUGIN_METADATA,
        segments,
        0,
        feature_set.manifest_parser_generator,
        is_completion_attempt=True,
    )
    if km is None:
        return None
    parser, _, at_depth_idx = km
    _info(f"Match leaf parser {at_depth_idx} -- {parser.__class__}")
    items = []
    if at_depth_idx + 1 >= len(segments):
        if isinstance(parser, DispatchingParserBase):
            if matched_key:
                items = [
                    CompletionItem(
                        maybe_quote_yaml_value(k)
                        if has_colon
                        else f"{maybe_quote_yaml_value(k)}:"
                    )
                    for k in parser.registered_keywords()
                    if k not in parent
                    and not isinstance(
                        parser.parser_for(k).parser,
                        DeclarativeValuelessKeywordInputParser,
                    )
                ]
            else:
                items = [
                    CompletionItem(maybe_quote_yaml_value(k))
                    for k in parser.registered_keywords()
                    if k not in parent
                    and isinstance(
                        parser.parser_for(k).parser,
                        DeclarativeValuelessKeywordInputParser,
                    )
                ]
        elif isinstance(parser, InPackageContextParser):
            binary_packages = ls.lint_state(doc).binary_packages
            if binary_packages is not None:
                items = [
                    CompletionItem(
                        maybe_quote_yaml_value(p)
                        if has_colon
                        else f"{maybe_quote_yaml_value(p)}:"
                    )
                    for p in binary_packages
                    if p not in parent
                ]
        elif isinstance(parser, DeclarativeMappingInputParser):
            if matched_key:
                _info("Match attributes")
                locked = set(parent)
                for mx in parser.mutually_exclusive_attributes:
                    if not mx.isdisjoint(parent.keys()):
                        locked.update(mx)
                for attr_name, attr in parser.manifest_attributes.items():
                    if not attr.conflicting_attributes.isdisjoint(parent.keys()):
                        locked.add(attr_name)
                        break
                items = [
                    CompletionItem(
                        maybe_quote_yaml_value(k)
                        if has_colon
                        else f"{maybe_quote_yaml_value(k)}:"
                    )
                    for k in parser.manifest_attributes
                    if k not in locked
                ]
            else:
                # Value
                key = segments[at_depth_idx] if len(segments) > at_depth_idx else None
                attr = parser.manifest_attributes.get(key)
                if attr is not None:
                    _info(f"Expand value / key: {key} -- {attr.attribute_type}")
                    items = completion_from_attr(
                        attr,
                        feature_set.manifest_parser_generator,
                        matched,
                    )
                else:
                    _info(
                        f"Expand value / key: {key} -- !! {list(parser.manifest_attributes)}"
                    )
        elif isinstance(parser, DeclarativeNonMappingInputParser):
            attr = parser.alt_form_parser
            items = completion_from_attr(
                attr,
                feature_set.manifest_parser_generator,
                matched,
            )
    return items


@lsp_hover(_DISPATCH_RULE)
def debputy_manifest_hover(
    ls: "DebputyLanguageServer",
    params: HoverParams,
) -> Optional[Hover]:
    return generic_yaml_hover(
        ls,
        params,
        lambda pg: pg.dispatchable_object_parsers[OPARSER_MANIFEST_ROOT],
    )
