"""Generated by eglot-python-preset."""

from typing import Any, cast

from rassumfrassum.frassum import LspLogic, Server
from rassumfrassum.json import JSON
from rassumfrassum.util import dmerge

SERVERS: list[list[str]] = __SERVERS__  # type: ignore[name-defined]
TY_CONFIGURATION: dict[str, Any] | None = __TY_CONFIGURATION__  # type: ignore[name-defined]
BASEDPYRIGHT_CONFIGURATION: dict[str, Any] | None = __BASEDPYRIGHT_CONFIGURATION__  # type: ignore[name-defined]
PYREFLY_CONFIGURATION: dict[str, Any] | None = __PYREFLY_CONFIGURATION__  # type: ignore[name-defined]


def _server_kind(name: str) -> str | None:
    base = name.lower().split("#", 1)[0]
    if "." in base:
        base = base.rsplit(".", 1)[0]
    if base in ("basedpyright", "basedpyright-langserver"):
        return "basedpyright"
    if base == "pyrefly":
        return "pyrefly"
    if base == "ruff":
        return "ruff"
    if base == "ty":
        return "ty"
    return None


def _merge_response_items(
    request_params: JSON,
    response_payload: JSON,
    sections: tuple[str, ...],
    override: dict[str, Any],
) -> None:
    if not isinstance(response_payload, list):
        return
    req_items = cast(list[dict[str, Any]], request_params.get("items", []))
    if len(response_payload) < len(req_items):
        response_payload.extend([None] * (len(req_items) - len(response_payload)))
    for i, item in enumerate(req_items):
        if item.get("section", "") in sections:
            existing = response_payload[i]
            if isinstance(existing, dict):
                response_payload[i] = dmerge(existing, override)
            else:
                response_payload[i] = dmerge({}, override)


class GeneratedPythonLogic(LspLogic):
    async def on_client_request(
        self, method: str, params: JSON, servers: list[Server]
    ):
        if method == "initialize" and TY_CONFIGURATION:
            params["initializationOptions"] = dmerge(
                params.get("initializationOptions") or {},
                TY_CONFIGURATION,
            )
        if method == "initialize" and PYREFLY_CONFIGURATION:
            params["initializationOptions"] = dmerge(
                params.get("initializationOptions") or {},
                PYREFLY_CONFIGURATION,
            )
        return await super().on_client_request(method, params, servers)

    async def on_client_response(
        self,
        method: str,
        request_params: JSON,
        response_payload: JSON,
        is_error: bool,
        server: Server,
    ) -> None:
        if method == "workspace/configuration" and not is_error:
            kind = _server_kind(server.name)
            if kind == "basedpyright" and BASEDPYRIGHT_CONFIGURATION:
                _merge_response_items(
                    request_params,
                    response_payload,
                    ("", "python"),
                    BASEDPYRIGHT_CONFIGURATION,
                )
            elif kind == "ty" and TY_CONFIGURATION:
                _merge_response_items(
                    request_params,
                    response_payload,
                    ("", "ty"),
                    TY_CONFIGURATION,
                )
        await super().on_client_response(
            method,
            request_params,
            response_payload,
            is_error,
            server,
        )


def servers():
    return SERVERS


def logic_class():
    return GeneratedPythonLogic
