from contextlib import contextmanager
import importlib.util
from pathlib import Path
import sys
import threading
import time
import types
from typing import Iterator


ADDON_DIR = Path(__file__).resolve().parents[1] / "addon" / "FreeCADMCP"
GUI_DISPATCH_PATH = ADDON_DIR / "rpc_server" / "gui_dispatch.py"
if str(ADDON_DIR) not in sys.path:
    sys.path.insert(0, str(ADDON_DIR))


class FakeSignal:
    def __init__(self) -> None:
        self.callback = None

    def connect(self, callback, *_args) -> None:
        self.callback = callback

    def emit(self) -> None:
        if self.callback is not None:
            self.callback()


class FakeStatusBar:
    def __init__(self) -> None:
        self.message = ""

    def showMessage(self, message: str, _timeout: int = 0) -> None:
        self.message = message

    def clearMessage(self) -> None:
        self.message = ""

    def currentMessage(self) -> str:
        return self.message


class FakeApplication:
    @staticmethod
    def mouseButtons() -> int:
        return 0

    @staticmethod
    def activePopupWidget() -> None:
        return None

    @staticmethod
    def activeModalWidget() -> None:
        return None

    @staticmethod
    def instance() -> "FakeApplication":
        return FakeApplication()

    def setOverrideCursor(self, _cursor) -> None:
        pass

    def restoreOverrideCursor(self) -> None:
        pass


@contextmanager
def load_gui_dispatch() -> Iterator[types.ModuleType]:
    module_names = ["FreeCAD", "FreeCADGui", "PySide"]
    missing = object()
    saved = {name: sys.modules.get(name, missing) for name in module_names}

    freecad = types.ModuleType("FreeCAD")
    freecad.Console = types.SimpleNamespace(PrintError=lambda _message: None)

    status_bar = FakeStatusBar()
    freecad_gui = types.ModuleType("FreeCADGui")
    freecad_gui.updateGui = lambda: None
    freecad_gui.getMainWindow = lambda: types.SimpleNamespace(
        statusBar=lambda: status_bar
    )

    qt_core = types.SimpleNamespace(
        QObject=object,
        Signal=FakeSignal,
        Qt=types.SimpleNamespace(
            QueuedConnection=0,
            NoButton=0,
            WaitCursor=0,
        ),
        QEventLoop=types.SimpleNamespace(
            ExcludeUserInputEvents=1,
            ExcludeSocketNotifiers=2,
        ),
        QThread=types.SimpleNamespace(msleep=lambda _delay: None),
        QTimer=types.SimpleNamespace(singleShot=lambda _delay, _callback: None),
    )
    qt_widgets = types.SimpleNamespace(QApplication=FakeApplication)
    pyside = types.ModuleType("PySide")
    pyside.QtCore = qt_core
    pyside.QtWidgets = qt_widgets

    sys.modules["FreeCAD"] = freecad
    sys.modules["FreeCADGui"] = freecad_gui
    sys.modules["PySide"] = pyside

    module_name = f"_gui_dispatch_test_{time.monotonic_ns()}"
    try:
        spec = importlib.util.spec_from_file_location(module_name, GUI_DISPATCH_PATH)
        if spec is None or spec.loader is None:
            raise ImportError(f"Cannot load gui_dispatch from {GUI_DISPATCH_PATH}")
        module = importlib.util.module_from_spec(spec)
        sys.modules[module_name] = module
        spec.loader.exec_module(module)
        yield module
    finally:
        sys.modules.pop(module_name, None)
        for name, value in saved.items():
            if value is missing:
                sys.modules.pop(name, None)
            else:
                sys.modules[name] = value


class ThreadedWaker:
    def __init__(self, gui_dispatch: types.ModuleType):
        self.gui_dispatch = gui_dispatch
        self.threads: list[threading.Thread] = []

    def wake(self) -> None:
        thread = threading.Thread(
            target=lambda: self.gui_dispatch.process_gui_tasks(),
            daemon=True,
        )
        thread.start()
        self.threads.append(thread)

    def join(self) -> None:
        for thread in self.threads:
            thread.join(timeout=1.0)


def test_running_timeout_blocks_followups_until_task_finishes() -> None:
    with load_gui_dispatch() as gui_dispatch:
        waker = ThreadedWaker(gui_dispatch)
        gui_dispatch._waker = waker
        started = threading.Event()
        release = threading.Event()

        def blocked_task() -> bool:
            started.set()
            release.wait(timeout=1.0)
            return True

        first = gui_dispatch.dispatch_to_gui(
            blocked_task,
            timeout=0.05,
            operation_name="remove_broken_feature",
        )
        assert started.is_set()
        assert first["code"] == "GUI_DISPATCH_STUCK"

        before = time.monotonic()
        second = gui_dispatch.dispatch_to_gui(
            lambda: True,
            timeout=1.0,
            operation_name="list_documents",
        )
        elapsed = time.monotonic() - before

        assert second["code"] == "GUI_DISPATCH_STUCK"
        assert elapsed < 0.1
        assert gui_dispatch.get_dispatch_status()["state"] == "stuck"

        release.set()
        waker.join()
        assert gui_dispatch.get_dispatch_status()["state"] == "healthy"

        third = gui_dispatch.dispatch_to_gui(
            lambda: "recovered",
            timeout=0.5,
            operation_name="recovered_call",
        )
        waker.join()

        assert third == "recovered"


def test_queued_timeout_cancels_task_without_marking_dispatch_stuck() -> None:
    with load_gui_dispatch() as gui_dispatch:
        ran = threading.Event()

        result = gui_dispatch.dispatch_to_gui(
            lambda: ran.set(),
            timeout=0.01,
            operation_name="stale_call",
        )
        gui_dispatch.process_gui_tasks()

        assert result["success"] is False
        assert "code" not in result
        assert "waiting for 'stale_call' to start" in result["error"]
        assert not ran.is_set()
        assert gui_dispatch.get_dispatch_status()["state"] == "healthy"


def test_run_budget_counts_from_task_start_not_from_enqueue() -> None:
    """A call queued behind a slow task must not lose its budget while waiting."""
    with load_gui_dispatch() as gui_dispatch:
        waker = ThreadedWaker(gui_dispatch)
        gui_dispatch._waker = waker
        first_started = threading.Event()
        release_first = threading.Event()
        results: dict[str, object] = {}

        def slow_task() -> str:
            first_started.set()
            release_first.wait(timeout=2.0)
            return "first"

        def run_first() -> None:
            results["first"] = gui_dispatch.dispatch_to_gui(
                slow_task, timeout=2.0, operation_name="slow_boolean"
            )

        first_thread = threading.Thread(target=run_first, daemon=True)
        first_thread.start()
        assert first_started.wait(timeout=1.0)

        # Second call: its own run takes ~0, but it has to wait 0.3s in the
        # queue. timeout=0.1 must still succeed because the wait is not billed.
        def run_second() -> None:
            results["second"] = gui_dispatch.dispatch_to_gui(
                lambda: "second",
                timeout=0.1,
                queue_timeout=2.0,
                operation_name="quick_query",
            )

        second_thread = threading.Thread(target=run_second, daemon=True)
        second_thread.start()
        time.sleep(0.3)
        assert "second" not in results  # still queued behind the slow task
        release_first.set()
        first_thread.join(timeout=2.0)
        second_thread.join(timeout=2.0)
        waker.join()

        assert results["first"] == "first"
        assert results["second"] == "second"
        assert gui_dispatch.get_dispatch_status()["state"] == "healthy"


def test_already_queued_call_survives_stuck_predecessor() -> None:
    """Fail-fast applies to new calls only; a queued call runs once the wedge clears."""
    with load_gui_dispatch() as gui_dispatch:
        waker = ThreadedWaker(gui_dispatch)
        gui_dispatch._waker = waker
        first_started = threading.Event()
        release_first = threading.Event()
        results: dict[str, object] = {}

        def stuck_task() -> bool:
            first_started.set()
            release_first.wait(timeout=2.0)
            return True

        def run_first() -> None:
            results["first"] = gui_dispatch.dispatch_to_gui(
                stuck_task, timeout=0.1, operation_name="wedged_op"
            )

        first_thread = threading.Thread(target=run_first, daemon=True)
        first_thread.start()
        assert first_started.wait(timeout=1.0)

        def run_second() -> None:
            results["second"] = gui_dispatch.dispatch_to_gui(
                lambda: "queued", timeout=0.1, queue_timeout=2.0,
                operation_name="queued_behind_wedge",
            )

        second_thread = threading.Thread(target=run_second, daemon=True)
        second_thread.start()
        first_thread.join(timeout=2.0)
        assert results["first"]["code"] == "GUI_DISPATCH_STUCK"
        assert gui_dispatch.get_dispatch_status()["state"] == "stuck"
        # A brand-new call is rejected immediately while the wedge persists.
        assert gui_dispatch.dispatch_to_gui(lambda: True, timeout=1.0)["code"] == "GUI_DISPATCH_STUCK"

        release_first.set()
        second_thread.join(timeout=2.0)
        waker.join()
        assert results["second"] == "queued"
        assert gui_dispatch.get_dispatch_status()["state"] == "healthy"


def test_run_deadline_does_not_restart_when_rpc_thread_resumes_late() -> None:
    with load_gui_dispatch() as dispatch:
        waker = ThreadedWaker(dispatch)
        entered, release = threading.Event(), threading.Event()

        def delayed_wake() -> None:
            waker.wake()
            assert entered.wait(1)
            time.sleep(0.3)  # Simulate delayed scheduling of the RPC thread.

        def task() -> bool:
            entered.set()
            release.wait(2)
            return True

        dispatch._waker = types.SimpleNamespace(wake=delayed_wake)
        before = time.monotonic()
        try:
            result = dispatch.dispatch_to_gui(task, timeout=0.3)
            elapsed = time.monotonic() - before
            assert result["code"] == "GUI_DISPATCH_STUCK"
            assert elapsed < 0.5  # The run deadline is not reset to another 0.3s.
        finally:
            release.set()
            waker.join()


def test_queue_deadline_includes_time_spent_waking_gui() -> None:
    with load_gui_dispatch() as dispatch:
        dispatch._waker = types.SimpleNamespace(wake=lambda: time.sleep(0.3))
        ran = threading.Event()
        before = time.monotonic()
        result = dispatch.dispatch_to_gui(ran.set, timeout=1, queue_timeout=0.3)
        elapsed = time.monotonic() - before
        assert result["success"] is False
        assert elapsed < 0.5
        dispatch.process_gui_tasks()
        assert not ran.is_set()


def test_system_exit_in_task_is_reported_instead_of_leaving_the_gui_loop() -> None:
    # A script that calls sys.exit() must fail its call, not quit FreeCAD:
    # SystemExit escaping the Qt slot that runs process_gui_tasks ends the app.
    with load_gui_dispatch() as dispatch:
        dispatch._waker = types.SimpleNamespace(
            wake=lambda: dispatch.process_gui_tasks()
        )

        def exiting_task() -> None:
            raise SystemExit(3)

        result = dispatch.dispatch_to_gui(exiting_task, timeout=1)

        assert result == "SystemExit: 3"
        assert dispatch.get_dispatch_status()["state"] == "healthy"
        assert dispatch.dispatch_to_gui(lambda: "next", timeout=1) == "next"


def test_system_exit_from_a_raw_queued_task_does_not_leave_the_gui_loop() -> None:
    with load_gui_dispatch() as dispatch:
        ran = threading.Event()

        def exiting_task() -> None:
            raise SystemExit(3)

        dispatch._rpc_request_queue.put(exiting_task)
        dispatch._rpc_request_queue.put(ran.set)
        dispatch.process_gui_tasks()

        assert ran.is_set()


def test_drain_leaves_a_message_shown_across_calls_alone() -> None:
    with load_gui_dispatch() as gui_dispatch:
        status_bar = gui_dispatch.FreeCADGui.getMainWindow().statusBar()
        gui_dispatch.post_to_gui(lambda: status_bar.showMessage("job running"))
        gui_dispatch.process_gui_tasks()
        assert status_bar.currentMessage() == "job running"

        # An unrelated call in between, then the job's clear in a later drain.
        gui_dispatch.post_to_gui(lambda: None)
        gui_dispatch.process_gui_tasks()
        assert status_bar.currentMessage() == "job running"
        gui_dispatch.post_to_gui(status_bar.clearMessage)
        gui_dispatch.process_gui_tasks()
        assert status_bar.currentMessage() == ""


def test_drain_shows_and_removes_its_own_note() -> None:
    with load_gui_dispatch() as gui_dispatch:
        status_bar = gui_dispatch.FreeCADGui.getMainWindow().statusBar()
        seen = []
        gui_dispatch.post_to_gui(lambda: seen.append(status_bar.currentMessage()))
        gui_dispatch.process_gui_tasks()
        assert seen == ["MCP: processing…"]
        assert status_bar.currentMessage() == ""


def test_post_to_gui_returns_without_waiting_for_a_busy_gui_thread() -> None:
    with load_gui_dispatch() as gui_dispatch:
        ran = threading.Event()
        before = time.monotonic()
        gui_dispatch.post_to_gui(ran.set)  # no waker: nothing drains the queue yet
        assert time.monotonic() - before < 0.1
        assert not ran.is_set()
        gui_dispatch.process_gui_tasks()
        assert ran.is_set()


def test_error_text_with_a_lone_surrogate_still_returns_the_error() -> None:
    with load_gui_dispatch() as gui_dispatch:
        logged = []

        def print_error(message: str) -> None:
            message.encode("utf-8")  # FreeCAD's PrintError fails like this
            logged.append(message)

        gui_dispatch.FreeCAD.Console.PrintError = print_error
        gui_dispatch._waker = ThreadedWaker(gui_dispatch)

        def fail() -> None:
            raise ValueError("bad \udcff")

        res = gui_dispatch.dispatch_to_gui(fail, timeout=2)
        gui_dispatch._waker.join()
        assert res == "ValueError: bad \udcff"
        assert logged and "bad \\udcff" in logged[0]
