import http.client
import logging
import base64
import math
import threading
import xmlrpc.client
from typing import Any

from .version import addon_version_warning, is_missing_method_fault


logger = logging.getLogger("FreeCADMCPserver")


class _TimeoutTransport(xmlrpc.client.Transport):
    """XML-RPC transport with a configurable socket timeout.

    The default Transport has no timeout, so a frozen FreeCAD GUI thread
    causes the MCP client to hang indefinitely (observed: 4+ minute waits).
    """
    def __init__(self, timeout: float = 30, **kwargs):
        super().__init__(**kwargs)
        self._timeout = timeout

    def request(self, host: Any, handler: str, request_body: bytes, verbose: bool = False) -> Any:
        # Transport.request retries disconnected requests. A modifying RPC can
        # already have committed before its response is lost, so never replay it.
        try:
            return self.single_request(host, handler, request_body, verbose)
        except (
            http.client.RemoteDisconnected, ConnectionResetError,
            ConnectionAbortedError, BrokenPipeError,
        ) as exc:
            raise ConnectionError(
                "RPC connection lost before a response; the operation may already have executed. "
                "Inspect document state before retrying a modifying call."
            ) from exc

    def make_connection(self, host):
        conn = super().make_connection(host)
        conn.timeout = self._timeout
        return conn


def _is_budget(value: Any, ceiling: float) -> bool:
    """True for a number of seconds in (0, ceiling]; NaN and infinities fail."""
    return (
        isinstance(value, (int, float))
        and not isinstance(value, bool)
        and 0 < value <= ceiling
    )


class FreeCADConnection:
    # Fallback run budgets for addons that do not report their own through
    # get_rpc_status; check_addon_version replaces them when they do.
    EXECUTE_CODE_TIMEOUT = 90
    MAX_EXECUTE_CODE_TIMEOUT = 1800
    RPC_TIMEOUT_MARGIN = 30
    # get_rpc_status never waits for the GUI thread, so a healthy addon answers
    # at once. The check runs while the MCP server starts, so a hung addon must
    # not hold up the session for the full connection timeout.
    VERSION_CHECK_TIMEOUT = 5

    def __init__(
        self,
        host: str = "localhost",
        port: int = 9875,
        timeout: float = 150,
        token: str | None = None,
    ):
        self.server_id: str | None = None
        self.compatibility: dict[str, Any] = {"state": "unchecked"}
        self._budget_lock = threading.Lock()
        self._uri = f"http://{host}:{port}"
        # A header, not URL userinfo: xmlrpc.client repeats the URL's host part,
        # userinfo included, in its repr and error messages, and tools return
        # those messages to the model.
        self._headers = [("Authorization", f"Bearer {token}")] if token else []
        if token and not token.isascii():
            encoded = base64.b64encode(f":{token}".encode("utf-8")).decode("ascii")
            self._headers = [("Authorization", f"Basic {encoded}")]
        self._timeout = timeout

    def _make_proxy(self, timeout: float) -> xmlrpc.client.ServerProxy:
        return xmlrpc.client.ServerProxy(
            self._uri,
            allow_none=True,
            transport=_TimeoutTransport(timeout=timeout, headers=self._headers),
        )

    def disconnect(self) -> None:
        """No idle connection is retained; each call closes its own transport."""

    def _call(self, method: str, *args: Any) -> Any:
        # ServerProxy caches an HTTPConnection and is not thread-safe. MCP 2.x
        # runs sync tools in worker threads, so even ordinary reads and writes
        # need a separate transport per call. Do not lock around a GUI request:
        # status/ping must remain usable while that request waits on FreeCAD.
        with self._make_proxy(self._timeout) as proxy:
            return getattr(proxy, method)(*args)

    def ping(self) -> bool:
        return self._call("ping")

    def get_rpc_status(self) -> dict[str, Any]:
        with self._make_proxy(self._timeout) as proxy:
            return proxy.get_rpc_status()

    def check_addon_version(self) -> str | None:
        """Compare the addon's version with this server and adopt its budgets.

        Returns a warning for an old, mismatched or unverified addon; None means compatible.
        """
        # Refresh for every tool admission. A cached client is configuration,
        # not proof that the listener is still the same process/generation.
        try:
            with self._make_proxy(self.VERSION_CHECK_TIMEOUT) as proxy:
                status = proxy.get_rpc_status()
        except Exception as e:
            self._adopt_budgets({})
            self.server_id = None
            if is_missing_method_fault(e):
                # Addons older than get_rpc_status reject the method outright.
                self.compatibility = {"state": "legacy"}
                self.server_id = None
                return addon_version_warning(None)
            logger.warning(f"Could not check the FreeCAD addon version: {e}")
            self.compatibility = {"state": "unknown", "error": str(e)}
            return f"FreeCAD addon compatibility is unknown: version check failed: {e}"
        if not isinstance(status, dict):
            self._adopt_budgets({})
            self.server_id = None
            self.compatibility = {"state": "unknown", "error": "Malformed status response"}
            return addon_version_warning({})
        self.server_id = status.get("server_id")
        self._adopt_budgets(status)
        notice = addon_version_warning(status)
        self.compatibility = {"state": "mismatch" if notice else "compatible",
                              "server_id": self.server_id,
                              "protocol_version": status.get("protocol_version")}
        return notice

    def _adopt_budgets(self, status: dict[str, Any]) -> None:
        budgets = {}
        for key, attr in (
            ("execute_code_timeout", "EXECUTE_CODE_TIMEOUT"),
            ("max_execute_code_timeout", "MAX_EXECUTE_CODE_TIMEOUT"),
        ):
            value = status.get(key)
            # Socket timeouts are derived from these budgets, so this client's
            # own ceiling bounds how long an addon's report can make it wait.
            if _is_budget(value, FreeCADConnection.MAX_EXECUTE_CODE_TIMEOUT):
                budgets[attr] = value
            else:
                budgets[attr] = getattr(type(self), attr)
        with self._budget_lock:
            for attr, value in budgets.items():
                setattr(self, attr, value)

    def create_document(self, name: str) -> dict[str, Any]:
        return self._call("create_document", name)

    def create_object(self, doc_name: str, obj_data: dict[str, Any]) -> dict[str, Any]:
        return self._call("create_object", doc_name, obj_data)

    def edit_object(self, doc_name: str, obj_name: str, obj_data: dict[str, Any]) -> dict[str, Any]:
        return self._call("edit_object", doc_name, obj_name, obj_data)

    def delete_object(self, doc_name: str, obj_name: str) -> dict[str, Any]:
        return self._call("delete_object", doc_name, obj_name)

    def reload_document(self, doc_name: str) -> dict[str, Any]:
        return self._call("reload_document", doc_name)

    def insert_part_from_library(self, relative_path: str) -> dict[str, Any]:
        return self._call("insert_part_from_library", relative_path)

    def execute_code(self, code: str, timeout: float | None = None) -> dict[str, Any]:
        # The addon permits a full queue budget followed by a full run budget.
        # Both default to EXECUTE_CODE_TIMEOUT, or to the caller's per-call
        # timeout, so the socket must outlast either budget.
        with self._budget_lock:
            run_budget = self.EXECUTE_CODE_TIMEOUT
            max_budget = self.MAX_EXECUTE_CODE_TIMEOUT
        if timeout is not None:
            try:
                run_budget = float(timeout)
            except (TypeError, ValueError, OverflowError) as exc:
                raise ValueError("timeout must be a positive finite number") from exc
            if isinstance(timeout, bool) or not math.isfinite(run_budget) or run_budget <= 0:
                raise ValueError("timeout must be a positive finite number")
            run_budget = min(run_budget, max_budget)
        socket_timeout = max(self._timeout, 2 * run_budget + self.RPC_TIMEOUT_MARGIN)
        with self._make_proxy(socket_timeout) as proxy:
            # Without an explicit timeout, call with a single argument so a
            # newer client keeps working against an addon that predates the
            # timeout parameter.
            if timeout is None:
                return proxy.execute_code(code)
            return proxy.execute_code(code, run_budget)

    def execute_code_async(self, code: str) -> dict[str, Any]:
        return self._call("execute_code_async", code)

    def get_async_status(self, job_id: str = "") -> dict[str, Any]:
        # Polling must not share an HTTP connection with a blocked GUI request.
        with self._make_proxy(self._timeout) as proxy:
            return proxy.get_async_status(job_id)

    def get_task_status(self, task_id: str | None = None) -> dict[str, Any]:
        return self._call("get_task_status", task_id)

    def get_active_screenshot(
        self,
        view_name: str = "Isometric",
        width: int | None = None,
        height: int | None = None,
        focus_object: str | None = None,
        doc_name: str | None = None,
    ) -> str | None:
        args = (view_name, width, height, focus_object)
        # Keep explicit active-view capture compatible with older addons.
        if doc_name is not None:
            args += (doc_name,)
        return self._call("get_active_screenshot", *args)

    def get_objects(self, doc_name: str) -> list[dict[str, Any]]:
        return self._call("get_objects", doc_name)

    def get_object(self, doc_name: str, obj_name: str) -> dict[str, Any]:
        return self._call("get_object", doc_name, obj_name)

    def get_parts_list(self) -> list[str]:
        return self._call("get_parts_list")

    def list_documents(self) -> list[str]:
        return self._call("list_documents")

    def run_fem_analysis(self, doc_name: str, analysis_name: str, timeout: int = 600) -> dict[str, Any]:
        if isinstance(timeout, bool) or not isinstance(timeout, int) or not 0 < timeout <= 2**31 - 1:
            raise ValueError("timeout must be an integer between 1 and 2147483647 seconds")
        # Both queueing and solving can consume `timeout` seconds each.
        socket_timeout = max(self._timeout, 2 * timeout + self.RPC_TIMEOUT_MARGIN)
        with self._make_proxy(socket_timeout) as proxy:
            return proxy.run_fem_analysis(doc_name, analysis_name, timeout)
