from typing import (
    Union,
    Any,
    Optional,
    List,
    Tuple,
    Iterable,
    TYPE_CHECKING,
    Callable,
    Sequence,
    get_origin,
    Literal,
    get_args,
)

from debputy.linting.lint_util import LintState
from debputy.lsp.diagnostics import LintSeverity
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.manifest_parser.declarative_parser import (
    DeclarativeMappingInputParser,
    ParserGenerator,
    AttributeDescription,
)
from debputy.manifest_parser.parser_doc import (
    render_rule,
    render_attribute_doc,
    doc_args_for_parser_doc,
)
from debputy.manifest_parser.tagging_types import DebputyDispatchableType
from debputy.manifest_parser.util import AttributePath
from debputy.plugin.api.feature_set import PluginProvidedFeatureSet
from debputy.plugin.api.impl import plugin_metadata_for_debputys_own_plugin
from debputy.plugin.api.impl_types import (
    DebputyPluginMetadata,
    DeclarativeInputParser,
    DispatchingParserBase,
    InPackageContextParser,
    ListWrappedDeclarativeInputParser,
)
from debputy.util import _info, _warn, detect_possible_typo
from debputy.yaml import MANIFEST_YAML
from debputy.yaml.compat import (
    Node,
    CommentedMap,
    LineCol,
    CommentedSeq,
    CommentedBase,
    YAMLError,
)

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

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


YAML_COMPLETION_HINT_KEY = "___COMPLETE:"
YAML_COMPLETION_HINT_VALUE = "___COMPLETE"
DEBPUTY_PLUGIN_METADATA = plugin_metadata_for_debputys_own_plugin()


def resolve_hover_text_for_value(
    feature_set: PluginProvidedFeatureSet,
    parser: DeclarativeMappingInputParser,
    plugin_metadata: DebputyPluginMetadata,
    segment: Union[str, int],
    matched: Any,
) -> Optional[str]:

    hover_doc_text: Optional[str] = None
    attr = parser.manifest_attributes.get(segment)
    attr_type = attr.attribute_type if attr is not None else None
    if attr_type is None:
        _info(f"Matched value for {segment} -- No attr or type")
        return None
    if isinstance(attr_type, type) and issubclass(attr_type, DebputyDispatchableType):
        parser_generator = feature_set.manifest_parser_generator
        parser = parser_generator.dispatch_parser_table_for(attr_type)
        if parser is None or not isinstance(matched, str):
            _info(
                f"Unknown parser for {segment} or matched is not a str -- {attr_type} {type(matched)=}"
            )
            return None
        subparser = parser.parser_for(matched)
        if subparser is None:
            _info(f"Unknown parser for {matched} (subparser)")
            return None
        hover_doc_text = render_rule(
            matched,
            subparser.parser,
            plugin_metadata,
        )
    else:
        _info(f"Unknown value: {matched} -- {segment}")
    return hover_doc_text


def resolve_hover_text(
    feature_set: PluginProvidedFeatureSet,
    parser: Optional[Union[DeclarativeInputParser[Any], DispatchingParserBase]],
    plugin_metadata: DebputyPluginMetadata,
    segments: List[Union[str, int]],
    at_depth_idx: int,
    matched: Any,
    matched_key: bool,
) -> Optional[str]:
    hover_doc_text: Optional[str] = None
    if at_depth_idx == len(segments):
        segment = segments[at_depth_idx - 1]
        _info(f"Matched {segment} at ==, {matched_key=} ")
        hover_doc_text = render_rule(
            segment,
            parser,
            plugin_metadata,
            is_root_rule=False,
        )
    elif at_depth_idx + 1 == len(segments) and isinstance(
        parser, DeclarativeMappingInputParser
    ):
        segment = segments[at_depth_idx]
        _info(f"Matched {segment} at -1, {matched_key=} ")
        if isinstance(segment, str):
            if not matched_key:
                hover_doc_text = resolve_hover_text_for_value(
                    feature_set,
                    parser,
                    plugin_metadata,
                    segment,
                    matched,
                )
            if matched_key or hover_doc_text is None:
                rule_name = _guess_rule_name(segments, at_depth_idx)
                hover_doc_text = _render_param_doc(
                    rule_name,
                    parser,
                    plugin_metadata,
                    segment,
                )
    else:
        _info(f"No doc: {at_depth_idx=} {len(segments)=}")

    return hover_doc_text


def as_hover_doc(
    ls: "DebputyLanguageServer",
    hover_doc_text: Optional[str],
) -> Optional[types.Hover]:
    if hover_doc_text is None:
        return None
    return types.Hover(
        contents=types.MarkupContent(
            kind=ls.hover_markup_format(
                types.MarkupKind.Markdown,
                types.MarkupKind.PlainText,
            ),
            value=hover_doc_text,
        ),
    )


def _render_param_doc(
    rule_name: str,
    declarative_parser: DeclarativeMappingInputParser,
    plugin_metadata: DebputyPluginMetadata,
    attribute: str,
) -> Optional[str]:
    attr = declarative_parser.source_attributes.get(attribute)
    if attr is None:
        return None

    doc_args, parser_doc = doc_args_for_parser_doc(
        rule_name,
        declarative_parser,
        plugin_metadata,
    )
    rendered_docs = render_attribute_doc(
        declarative_parser,
        declarative_parser.source_attributes,
        declarative_parser.input_time_required_parameters,
        declarative_parser.at_least_one_of,
        parser_doc,
        doc_args,
        is_interactive=True,
        rule_name=rule_name,
    )

    for attributes, rendered_doc in rendered_docs:
        if attribute in attributes:
            full_doc = [
                f"# Attribute `{attribute}`",
                "",
            ]
            full_doc.extend(rendered_doc)

            return "\n".join(full_doc)
    return None


def _guess_rule_name(segments: List[Union[str, int]], idx: int) -> str:
    orig_idx = idx
    idx -= 1
    while idx >= 0:
        segment = segments[idx]
        if isinstance(segment, str):
            return segment
        idx -= 1
    _warn(f"Unable to derive rule name from {segments} [{orig_idx}]")
    return "<Bug: unknown rule name>"


def is_at(position: types.Position, lc_pos: Tuple[int, int]) -> bool:
    return position.line == lc_pos[0] and position.character == lc_pos[1]


def is_before(position: types.Position, lc_pos: Tuple[int, int]) -> bool:
    line, column = lc_pos
    if position.line < line:
        return True
    if position.line == line and position.character < column:
        return True
    return False


def is_after(position: types.Position, lc_pos: Tuple[int, int]) -> bool:
    line, column = lc_pos
    if position.line > line:
        return True
    if position.line == line and position.character > column:
        return True
    return False


def word_range_at_position(
    lines: List[str],
    line_no: int,
    char_offset: int,
) -> TERange:
    line = lines[line_no]
    line_len = len(line)
    start_idx = char_offset
    end_idx = char_offset

    for i in range(end_idx, line_len):
        end_idx = i
        if line[i].isspace():
            break

    for i in range(start_idx, -1, -1):
        if i > 0 and line[i].isspace():
            break
        start_idx = i

    return TERange(
        TEPosition(line_no, start_idx),
        TEPosition(line_no, end_idx),
    )


def _escape(v: str) -> str:
    return '"' + v.replace("\n", "\\n") + '"'


def insert_complete_marker_snippet(
    lines: List[str],
    server_position: types.Position,
) -> bool:
    _info(f"Complete at {server_position}")
    line_no = server_position.line
    line = lines[line_no] if line_no < len(lines) else ""
    pos_rhs = (
        line[server_position.character :]
        if server_position.character < len(line)
        else ""
    )
    if pos_rhs and not pos_rhs.isspace():
        _info(f"No insertion: {_escape(line[server_position.character:])}")
        return False
    lhs_ws = line[: server_position.character]
    lhs = lhs_ws.strip()
    if lhs.endswith(":"):
        _info("Insertion of value (key seen)")
        new_line = line[: server_position.character] + YAML_COMPLETION_HINT_VALUE + "\n"
    elif lhs.startswith("-"):
        _info("Insertion of key or value (list item)")
        # Respect the provided indentation
        snippet = (
            YAML_COMPLETION_HINT_KEY if ":" not in lhs else YAML_COMPLETION_HINT_VALUE
        )
        new_line = line[: server_position.character] + snippet + "\n"
    elif not lhs or (lhs_ws and not lhs_ws[0].isspace()):
        _info(f"Insertion of key or value: {_escape(line[server_position.character:])}")
        # Respect the provided indentation
        snippet = (
            YAML_COMPLETION_HINT_KEY if ":" not in lhs else YAML_COMPLETION_HINT_VALUE
        )
        new_line = line[: server_position.character] + snippet + "\n"
    elif lhs.isalpha() and ":" not in lhs:
        _info(f"Expanding value to a key: {_escape(line[server_position.character:])}")
        # Respect the provided indentation
        new_line = line[: server_position.character] + YAML_COMPLETION_HINT_KEY + "\n"
    else:
        c = (
            line[server_position.character]
            if server_position.character < len(line)
            else "(OOB)"
        )
        _info(f"Not touching line: {_escape(line)} -- {_escape(c)}")
        return False
    _info(f'Evaluating complete on synthetic line: "{new_line}"')
    if line_no < len(lines):
        lines[line_no] = new_line
    elif line_no == len(lines):
        lines.append(new_line)
    else:
        return False
    return True


def yaml_key_range(
    key: str,
    line: int,
    col: int,
) -> "TERange":
    key_len = len(key) if key else 1
    return TERange.between(
        TEPosition(line, col),
        TEPosition(line, col + key_len),
    )


def yaml_flag_unknown_key(
    lint_state: LintState,
    key: Optional[str],
    expected_keys: Iterable[str],
    line: int,
    col: int,
    *,
    message_format: str = 'Unknown or unsupported key "{key}".',
    unknown_keys_diagnostic_severity: Optional[LintSeverity] = "error",
) -> Optional[str]:
    key_range = yaml_key_range(key, line, col)

    candidates = detect_possible_typo(key, expected_keys) if key is not None else ()
    extra = ""
    corrected_key = None
    if candidates:
        extra = f' It looks like a typo of "{candidates[0]}".'
        # TODO: We should be able to tell that `install-doc` and `install-docs` are the same.
        #  That would enable this to work in more cases.
        corrected_key = candidates[0] if len(candidates) == 1 else None
        if unknown_keys_diagnostic_severity is None:
            message_format = f"Possible typo of {candidates[0]}."
            extra = ""
    elif unknown_keys_diagnostic_severity is None:
        return None

    if key is None:
        message_format = "Missing key"
    if unknown_keys_diagnostic_severity is not None:
        lint_state.emit_diagnostic(
            key_range,
            message_format.format(key=key) + extra,
            unknown_keys_diagnostic_severity,
            "debputy",
            quickfixes=[propose_correct_text_quick_fix(n) for n in candidates],
        )
    return corrected_key


def resolve_keyword(
    current_parser: Union[DeclarativeInputParser[Any], DispatchingParserBase],
    current_plugin: DebputyPluginMetadata,
    segments: List[Union[str, int]],
    segment_idx: int,
    parser_generator: ParserGenerator,
    *,
    is_completion_attempt: bool = False,
) -> Optional[
    Tuple[
        Union[DeclarativeInputParser[Any], DispatchingParserBase],
        DebputyPluginMetadata,
        int,
    ]
]:
    if segment_idx >= len(segments):
        return current_parser, current_plugin, segment_idx
    current_segment = segments[segment_idx]
    if isinstance(current_parser, ListWrappedDeclarativeInputParser):
        if isinstance(current_segment, int):
            current_parser = current_parser.delegate
            segment_idx += 1
            if segment_idx >= len(segments):
                return current_parser, current_plugin, segment_idx
            current_segment = segments[segment_idx]

    if not isinstance(current_segment, str):
        return None

    if is_completion_attempt and current_segment.endswith(
        (YAML_COMPLETION_HINT_KEY, YAML_COMPLETION_HINT_VALUE)
    ):
        return current_parser, current_plugin, segment_idx

    if isinstance(current_parser, InPackageContextParser):
        return resolve_keyword(
            current_parser.delegate,
            current_plugin,
            segments,
            segment_idx + 1,
            parser_generator,
            is_completion_attempt=is_completion_attempt,
        )
    elif isinstance(current_parser, DispatchingParserBase):
        if not current_parser.is_known_keyword(current_segment):
            if is_completion_attempt:
                return current_parser, current_plugin, segment_idx
            return None
        subparser = current_parser.parser_for(current_segment)
        segment_idx += 1
        if segment_idx < len(segments):
            return resolve_keyword(
                subparser.parser,
                subparser.plugin_metadata,
                segments,
                segment_idx,
                parser_generator,
                is_completion_attempt=is_completion_attempt,
            )
        return subparser.parser, subparser.plugin_metadata, segment_idx
    elif isinstance(current_parser, DeclarativeMappingInputParser):
        attr = current_parser.manifest_attributes.get(current_segment)
        attr_type = attr.attribute_type if attr is not None else None
        if (
            attr_type is not None
            and isinstance(attr_type, type)
            and issubclass(attr_type, DebputyDispatchableType)
        ):
            subparser = parser_generator.dispatch_parser_table_for(attr_type)
            if subparser is not None and (
                is_completion_attempt or segment_idx + 1 < len(segments)
            ):
                return resolve_keyword(
                    subparser,
                    current_plugin,
                    segments,
                    segment_idx + 1,
                    parser_generator,
                    is_completion_attempt=is_completion_attempt,
                )
        return current_parser, current_plugin, segment_idx
    else:
        _info(f"Unknown parser: {current_parser.__class__}")
    return None


def _trace_cursor(
    content: Any,
    attribute_path: AttributePath,
    server_position: types.Position,
) -> Optional[Tuple[bool, AttributePath, Any, Any]]:
    matched_key: Optional[Union[str, int]] = None
    matched: Optional[Node] = None
    matched_was_key: bool = False

    if isinstance(content, CommentedMap):
        dict_lc: LineCol = content.lc
        for k, v in content.items():
            k_lc = dict_lc.key(k)
            if is_before(server_position, k_lc):
                break
            v_lc = dict_lc.value(k)
            if is_before(server_position, v_lc):
                # TODO: Handle ":" and "whitespace"
                matched = k
                matched_key = k
                matched_was_key = True
                break
            matched = v
            matched_key = k
    elif isinstance(content, CommentedSeq):
        list_lc: LineCol = content.lc
        for idx, value in enumerate(content):
            i_lc = list_lc.item(idx)
            if is_before(server_position, i_lc):
                break
            matched_key = idx
            matched = value

    if matched is not None:
        assert matched_key is not None
        sub_path = attribute_path[matched_key]
        if not matched_was_key and isinstance(matched, CommentedBase):
            return _trace_cursor(matched, sub_path, server_position)
        return matched_was_key, sub_path, matched, content
    return None


def maybe_quote_yaml_value(v: str) -> str:
    if v and v[0].isdigit():
        try:
            float(v)
            return f"'{v}'"
        except ValueError:
            pass
    return v


def _complete_value(v: Any) -> str:
    if isinstance(v, str):
        return maybe_quote_yaml_value(v)
    return str(v)


def completion_from_attr(
    attr: AttributeDescription,
    pg: ParserGenerator,
    matched: Any,
) -> Optional[Union[types.CompletionList, Sequence[types.CompletionItem]]]:
    type_mapping = pg.get_mapped_type_from_target_type(attr.attribute_type)
    if type_mapping is not None:
        attr_type = type_mapping.source_type
    else:
        attr_type = attr.attribute_type

    orig = get_origin(attr_type)
    valid_values: Sequence[Any] = tuple()

    if orig == Literal:
        valid_values = get_args(attr_type)
    elif orig == bool or attr.attribute_type == bool:
        valid_values = ("true", "false")
    elif isinstance(orig, type) and issubclass(orig, DebputyDispatchableType):
        parser = pg.dispatch_parser_table_for(orig)
        _info(f"M: {parser}")

    if matched in valid_values:
        _info(f"Already filled: {matched} is one of {valid_values}")
        return None
    if valid_values:
        return [types.CompletionItem(_complete_value(x)) for x in valid_values]
    return None


def generic_yaml_hover(
    ls: "DebputyLanguageServer",
    params: types.HoverParams,
    root_parser_initializer: Callable[
        [ParserGenerator], Union[DeclarativeInputParser[Any], DispatchingParserBase]
    ],
) -> Optional[types.Hover]:
    doc = ls.workspace.get_text_document(params.text_document.uri)
    lines = doc.lines
    position_codec = doc.position_codec
    server_position = position_codec.position_from_client_units(lines, params.position)

    try:
        content = MANIFEST_YAML.load("".join(lines))
    except YAMLError:
        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, _ = m
    _info(f"Matched path: {matched} (path: {attr_path.path}) [{matched_key=}]")

    feature_set = ls.plugin_feature_set
    parser_generator = feature_set.manifest_parser_generator
    root_parser = root_parser_initializer(parser_generator)
    segments = list(attr_path.path_segments())
    km = resolve_keyword(
        root_parser,
        DEBPUTY_PLUGIN_METADATA,
        segments,
        0,
        parser_generator,
    )
    if km is None:
        _info("No keyword match")
        return None
    parser, plugin_metadata, at_depth_idx = km
    _info(f"Match leaf parser {at_depth_idx}/{len(segments)} -- {parser.__class__}")
    hover_doc_text = resolve_hover_text(
        feature_set,
        parser,
        plugin_metadata,
        segments,
        at_depth_idx,
        matched,
        matched_key,
    )
    return as_hover_doc(ls, hover_doc_text)
