from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
import importlib.util
import io
from pathlib import Path
import sys
import threading
import time
import types
from xmlrpc.client import Fault

import pytest

from test_gui_dispatch import load_gui_dispatch, ThreadedWaker
from test_rpc_concurrency import client, running_server


RPC_PATH = (
    Path(__file__).resolve().parents[1]
    / "addon" / "FreeCADMCP" / "rpc_server" / "rpc_server.py"
)


@pytest.fixture
def rpc_module(monkeypatch: pytest.MonkeyPatch) -> Iterator[types.ModuleType]:
    """Exercise real RPC handlers and dispatch with only FreeCAD/Qt stubbed."""
    with load_gui_dispatch() as dispatch:
        freecad = dispatch.FreeCAD
        freecad.Console.PrintMessage = lambda _message: None
        freecad.Console.PrintWarning = lambda _message: None
        document = types.SimpleNamespace(
            Objects=[types.SimpleNamespace(Name="Box")],
            getObject=lambda name: types.SimpleNamespace(Name=name) if name == "Box" else None,
        )

        def get_document(name: str) -> object:
            if name != "Doc":
                raise NameError(name)
            return document

        freecad.getDocument = get_document
        freecad.listDocuments = lambda: {"Doc": document}
        freecad.closeDocument = lambda _name: None
        freecad.openDocument = lambda _path: document
        stubs = {
            "gui_dispatch": dispatch,
            "commands": types.SimpleNamespace(
                register_commands=lambda: None, schedule_toggle_sync=lambda: None
            ),
            "fem_executor": types.SimpleNamespace(run_fem_analysis=lambda *_args: None),
            "object_factory": types.SimpleNamespace(
                create_object_gui=lambda *_args: None, edit_object_gui=lambda *_args: None
            ),
            "property_mapper": types.SimpleNamespace(Object=object),
            "parts_library": types.SimpleNamespace(
                get_parts_list=lambda: [], insert_part_from_library=lambda _path: None
            ),
            "serialize": types.SimpleNamespace(serialize_object=lambda obj: {"Name": obj.Name}),
            "settings": types.SimpleNamespace(load_settings=lambda: {}, save_settings=lambda _: None),
            "view_manager": types.SimpleNamespace(
                get_displayed_3d_view=lambda: None,
                save_active_screenshot=lambda *_args: True,
            ),
        }
        with monkeypatch.context() as patch:
            for name, stub in stubs.items():
                patch.setitem(sys.modules, f"rpc_server.{name}", stub)
            spec = importlib.util.spec_from_file_location("_rpc_handler_test", RPC_PATH)
            assert spec is not None and spec.loader is not None
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
            waker = ThreadedWaker(dispatch)
            dispatch._waker = waker
            module.test_dispatch = dispatch
            async_threads: list[threading.Thread] = []

            def worker_thread(*args, **kwargs) -> threading.Thread:
                thread = threading.Thread(*args, **kwargs)
                async_threads.append(thread)
                return thread

            module.threading = types.SimpleNamespace(Thread=worker_thread)
            try:
                yield module
            finally:
                for thread in async_threads:
                    thread.join(timeout=2)
                    assert not thread.is_alive()
                waker.join()


def test_script_names_cannot_replace_rpc_internals(rpc_module: types.ModuleType) -> None:
    rpc = rpc_module.FreeCADRPC()
    original_dispatch = rpc_module.dispatch_to_gui
    original_serializer = rpc_module.serialize_object
    result = rpc.execute_code(
        "dispatch_to_gui = None\nserialize_object = None\n"
        "FreeCAD = None\nFreeCADGui = None\nshared_value = 41"
    )
    assert result["success"] is True
    assert rpc_module.dispatch_to_gui is original_dispatch
    assert rpc_module.serialize_object is original_serializer
    result = rpc.execute_code("print(shared_value + 1)")
    assert result["success"] is True
    assert result["message"].endswith("42\n")
    assert rpc.get_object("Doc", "Box") == {"Name": "Box"}


def test_sync_script_is_rejected_while_async_namespace_is_owned(
    rpc_module: types.ModuleType,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    release = threading.Event()
    rpc_module.FreeCAD.audit_go = release
    started = rpc.execute_code_async("App.audit_go.wait(3); shared = 42")
    assert started["success"] is True
    try:
        reply = rpc.execute_code("shared = 99")
        assert reply["code"] == "SCRIPT_BUSY"
        assert reply["mutation_outcome"] == "not_started"
        assert rpc.get_object("Doc", "Box") == {"Name": "Box"}
    finally:
        release.set()
    assert wait_for_job(rpc, started["job_id"])["state"] == "done"
    assert rpc.execute_code("print(shared)")["message"].endswith("42\n")


def test_timed_out_script_keeps_capture_until_it_finishes(
    rpc_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch,
) -> None:
    console = io.StringIO()
    monkeypatch.setattr(sys, "stdout", console)
    release = threading.Event()
    rpc_module.FreeCAD.audit_release = release
    rpc = rpc_module.FreeCADRPC()
    try:
        reply = rpc.execute_code(
            'FreeCAD.audit_release.wait(3)\nprint("late script output")', timeout=0.02
        )
        assert reply["success"] is False
        print("console while task is running")
    finally:
        release.set()
        rpc_module.test_dispatch._waker.join()
    assert sys.stdout is console
    assert console.getvalue() == "console while task is running\n"
    assert rpc.execute_code('print("next call")')["message"].endswith("next call\n")


@pytest.mark.parametrize(
    ("code", "error"),
    [
        ("import sys; sys.exit(3)", "SystemExit: 3"),
        ('raise SystemExit("stop")', "SystemExit: stop"),
        ("raise KeyboardInterrupt()", "KeyboardInterrupt:"),
    ],
)
def test_script_exit_fails_the_call_and_preserves_rpc_dispatch(
    rpc_module: types.ModuleType, code: str, error: str,
) -> None:
    # Run the Qt callback synchronously so an escaping BaseException fails
    # this test instead of merely terminating a test worker thread.
    rpc_module.test_dispatch._waker = types.SimpleNamespace(
        wake=lambda: rpc_module.test_dispatch.process_gui_tasks()
    )
    rpc = rpc_module.FreeCADRPC()
    stdout = sys.stdout

    result = rpc.execute_code(code)

    assert result["success"] is False
    assert error in result["error"]
    assert sys.stdout is stdout
    assert rpc.get_rpc_status()["gui_dispatch"]["state"] == "healthy"
    assert rpc.get_object("Doc", "Box") == {"Name": "Box"}
    followup = rpc.execute_code('print("still running")')
    assert followup["success"] is True
    assert followup["message"].endswith("still running\n")


def test_async_scripts_share_variables_without_replacing_dispatch(
    rpc_module: types.ModuleType,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    original_dispatch = rpc_module.dispatch_to_gui
    done = threading.Event()
    rpc_module.FreeCAD.async_done = done
    assert rpc.execute_code("shared_value = 40")["success"] is True
    assert rpc.execute_code_async(
        "dispatch_to_gui = None\nshared_value += 2\nFreeCAD.async_done.set()"
    )["success"] is True
    assert done.wait(2)
    assert rpc_module.dispatch_to_gui is original_dispatch
    result = rpc.execute_code(
        "assert App is FreeCAD\nassert Gui is FreeCADGui\nprint(shared_value)"
    )
    assert result["success"] is True
    assert result["message"].endswith("42\n")


def test_async_commit_runs_document_writes_on_the_gui_thread(
    rpc_module: types.ModuleType,
) -> None:
    """Document writes must land on the GUI thread, not the worker thread."""
    rpc = rpc_module.FreeCADRPC()
    done = threading.Event()
    rpc_module.FreeCAD.async_done = done
    rpc_module.FreeCAD.test_threads = {}
    assert rpc.execute_code_async(
        "import threading\n"
        "FreeCAD.test_threads['worker'] = threading.current_thread().name\n"
        "def apply():\n"
        "    FreeCAD.test_threads['commit'] = threading.current_thread().name\n"
        "    return 'applied'\n"
        "FreeCAD.test_threads['result'] = commit(apply)\n"
        "FreeCAD.async_done.set()"
    )["success"] is True
    assert done.wait(2)
    threads = rpc_module.FreeCAD.test_threads
    assert threads["result"] == "applied"
    # The worker runs off-thread; commit hands the write to the dispatch thread.
    assert threads["commit"] != threads["worker"]


def test_scripts_are_not_admitted_while_a_previous_gui_script_is_stuck(
    rpc_module: types.ModuleType,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    health = rpc_module.test_dispatch._dispatch_health
    health.start(200, "execute_code")
    health.mark_timed_out(200, 90)
    reply = rpc.execute_code_async("should_not_run = True")
    assert reply["code"] == "SCRIPT_UNAVAILABLE"
    assert reply["mutation_outcome"] == "not_started"
    assert "should_not_run" not in rpc_module._EXEC_NAMESPACE


def test_saved_functions_can_commit_in_later_async_scripts(
    rpc_module: types.ModuleType,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    done = threading.Event()
    rpc_module.FreeCAD.async_done = done
    assert rpc.execute_code_async(
        "shared_value = 7\n"
        "def apply_later():\n"
        "    return commit(lambda: shared_value)\n"
        "FreeCAD.async_done.set()"
    )["success"] is True
    assert done.wait(2)
    assert rpc.execute_code("shared_value = 99")["success"] is True
    done.clear()
    assert rpc.execute_code_async(
        "FreeCAD.test_result = apply_later()\nFreeCAD.async_done.set()"
    )["success"] is True
    assert done.wait(2)
    assert rpc_module.FreeCAD.test_result == 99


def test_async_completion_preserves_state_and_rejects_concurrent_writes(
    rpc_module: types.ModuleType,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    entered, release, done = threading.Event(), threading.Event(), threading.Event()
    rpc_module.FreeCAD.test_entered = entered
    rpc_module.FreeCAD.test_release = release
    rpc_module.FreeCAD.Console.PrintMessage = (
        lambda message: done.set() if message == "Async code execution completed.\n" else None
    )
    assert rpc.execute_code("shared_value = 1\nobsolete = True")["success"] is True
    assert rpc.execute_code_async(
        "FreeCAD.test_entered.set()\nFreeCAD.test_release.wait(2)\n"
        "del obsolete\nasync_value = 42"
    )["success"] is True
    try:
        assert entered.wait(2)
        assert rpc.execute_code("shared_value = 99")["code"] == "SCRIPT_BUSY"
    finally:
        release.set()
    assert done.wait(2)
    result = rpc.execute_code(
        "assert shared_value == 1\nassert 'obsolete' not in globals()\nassert async_value == 42"
    )
    assert result["success"] is True, result


def test_async_exception_preserves_completed_assignments(
    rpc_module: types.ModuleType,
) -> None:
    done = threading.Event()
    rpc_module.FreeCAD.Console.PrintError = lambda _message: done.set()
    rpc = rpc_module.FreeCADRPC()
    assert rpc.execute_code_async("partial_result = 42\nraise ValueError('failed')")["success"]
    assert done.wait(2)
    assert rpc.execute_code("print(partial_result)")["message"].endswith("42\n")


@pytest.mark.parametrize("code", ["commit(lambda: 7)", "commit(lambda: commit(lambda: 7))"])
def test_commit_rejects_gui_thread_use_without_dispatching(
    rpc_module: types.ModuleType, code: str,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    if code == "commit(lambda: 7)":
        # Synchronous scripts already run on the GUI thread.
        result = rpc.execute_code(code)
        assert result["success"] is False
        assert "only available inside execute_code_async" in result["error"]
    else:
        done = threading.Event()
        errors: list[str] = []
        rpc_module.FreeCAD.Console.PrintError = lambda message: (errors.append(message), done.set())
        assert rpc.execute_code_async(code)["success"]
        assert done.wait(2)
        assert any("only available inside execute_code_async" in error for error in errors)


@pytest.mark.parametrize("value", [None, "error-looking text", {"success": False, "error": "data"}])
def test_commit_preserves_callback_return_values(
    rpc_module: types.ModuleType, value: object,
) -> None:
    done = threading.Event()
    rpc_module.FreeCAD.test_value = value
    rpc_module.FreeCAD.async_done = done
    assert rpc_module.FreeCADRPC().execute_code_async(
        "FreeCAD.test_result = commit(lambda: FreeCAD.test_value)\nFreeCAD.async_done.set()"
    )["success"]
    assert done.wait(2)
    assert rpc_module.FreeCAD.test_result == value


@pytest.mark.parametrize(
    ("method", "args", "expected"),
    [
        ("list_documents", (), ["Doc"]),
        ("get_objects", ("Doc",), [{"Name": "Box"}]),

        ("get_object", ("Doc", "Box"), {"Name": "Box"}),


    ],
)
def test_queries_use_gui_dispatch_and_keep_response_shapes(
    rpc_module: types.ModuleType, method: str, args: tuple, expected: object,
) -> None:
    dispatched: list[str] = []
    rpc = rpc_module.FreeCADRPC()
    original_dispatch = rpc_module.dispatch_to_gui

    def dispatch(task, **kwargs):
        dispatched.append(kwargs["operation_name"])
        return original_dispatch(task, **kwargs)

    rpc_module.dispatch_to_gui = dispatch
    assert getattr(rpc, method)(*args) == expected
    assert dispatched == [method]


@pytest.mark.parametrize(
    ("method", "args"),
    [("list_documents", ()), ("get_objects", ("Doc",)), ("get_object", ("Doc", "Box"))],
)
def test_queries_fail_without_touching_a_wedged_document(
    rpc_module: types.ModuleType, method: str, args: tuple,
) -> None:
    health = rpc_module.test_dispatch._dispatch_health
    health.start(100, "execute_code")
    health.mark_timed_out(100, 90)

    def unexpected_read(*_args):
        pytest.fail("Document was read while GUI dispatch was stuck")

    rpc_module.FreeCAD.getDocument = unexpected_read
    rpc_module.FreeCAD.listDocuments = unexpected_read
    with pytest.raises(Fault, match="GUI_DISPATCH_STUCK.*execute_code"):
        getattr(rpc_module.FreeCADRPC(), method)(*args)


def test_status_and_document_reads_during_real_dispatch(
    rpc_module: types.ModuleType,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    rpc.EXECUTE_CODE_TIMEOUT = 0.5
    entered, release, read = threading.Event(), threading.Event(), threading.Event()
    rpc_module.FreeCAD.test_entered = entered
    rpc_module.FreeCAD.test_release = release
    rpc_module.FreeCAD.listDocuments = lambda: (read.set() or {"Doc": object()})
    with running_server(rpc) as (host, port), ThreadPoolExecutor(max_workers=2) as workers:
        def request(method: str, *args):
            with client(host, port, 5) as proxy:
                return getattr(proxy, method)(*args)

        execution = workers.submit(
            request, "execute_code",
            "FreeCAD.test_entered.set()\nFreeCAD.test_release.wait(5)",
        )
        try:
            assert entered.wait(2)
            status = request("get_rpc_status")
            assert status["gui_dispatch"]["state"] == "busy"
            assert status["gui_dispatch"]["operation"] == "execute_code"
            query = workers.submit(request, "list_documents")
            # The query must not inspect document state until execution ends.
            assert not read.wait(0.1)
            assert execution.result(timeout=2)["code"] == "GUI_DISPATCH_STUCK"
            assert request("get_rpc_status")["gui_dispatch"]["state"] == "stuck"
            with pytest.raises(Fault, match="GUI_DISPATCH_STUCK"):
                request("get_objects", "Doc")
            release.set()
            assert query.result(timeout=2) == ["Doc"]
            assert read.is_set()
            assert request("get_rpc_status")["gui_dispatch"]["state"] == "healthy"
            assert request("get_object", "Doc", "Box") == {"Name": "Box"}
        finally:
            release.set()


def test_execute_code_uses_default_timeout_when_none_given(
    rpc_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch
) -> None:
    rpc = rpc_module.FreeCADRPC()
    seen: list[float] = []
    real = rpc_module.dispatch_to_gui

    def spy(task, timeout=60, operation_name=None, **kwargs):
        seen.append(timeout)
        return real(task, timeout=timeout, operation_name=operation_name, **kwargs)

    monkeypatch.setattr(rpc_module, "dispatch_to_gui", spy)
    assert rpc.execute_code("x = 1")["success"] is True
    assert seen == [rpc_module.FreeCADRPC.EXECUTE_CODE_TIMEOUT]


def test_execute_code_honours_caller_timeout_and_caps_it(
    rpc_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch
) -> None:
    rpc = rpc_module.FreeCADRPC()
    seen: list[float] = []
    real = rpc_module.dispatch_to_gui

    def spy(task, timeout=60, operation_name=None, **kwargs):
        seen.append(timeout)
        return real(task, timeout=timeout, operation_name=operation_name, **kwargs)

    monkeypatch.setattr(rpc_module, "dispatch_to_gui", spy)
    assert rpc.execute_code("x = 1", 300)["success"] is True
    assert rpc.execute_code("x = 1", "240")["success"] is True
    assert rpc.execute_code("x = 1", 10**9)["success"] is True
    assert seen == [300.0, 240.0, rpc_module.FreeCADRPC.MAX_EXECUTE_CODE_TIMEOUT]


@pytest.mark.parametrize("bad", ["soon", None.__class__, 0, -5])
def test_execute_code_rejects_invalid_timeout(
    rpc_module: types.ModuleType, bad: object
) -> None:
    rpc = rpc_module.FreeCADRPC()
    if bad is None.__class__:
        bad = object()
    result = rpc.execute_code("x = 1", bad)
    assert result["success"] is False
    assert "invalid timeout" in result["error"]


def test_async_failure_is_readable_through_get_async_status(
    rpc_module: types.ModuleType,
) -> None:
    done = threading.Event()
    rpc_module.FreeCAD.Console.PrintError = lambda _message: done.set()
    rpc_module.FreeCAD.Console.PrintWarning = lambda _message: None
    rpc = rpc_module.FreeCADRPC()
    started = rpc.execute_code_async("partial = 1\nraise ValueError('Null shape')")
    job_id = started["job_id"]
    assert started["success"] is True and job_id
    assert done.wait(2)
    for _ in range(50):
        job = rpc.get_async_status(job_id)["job"]
        if job["state"] != "running":
            break
        threading.Event().wait(0.02)
    assert job["state"] == "failed"
    assert job["error"] == "ValueError: Null shape"
    assert 'line 2, in <module>' in job["traceback"]
    assert rpc.get_async_status("nope") == {"success": False, "error": "unknown async job: nope"}
    assert [j["id"] for j in rpc.get_async_status()["jobs"]] == [job_id]
    assert rpc.get_rpc_status()["async_jobs_running"] == []


def wait_for_job(rpc: object, job_id: str) -> dict:
    deadline = time.monotonic() + 2
    while True:
        job = rpc.get_async_status(job_id)["job"]
        if job["state"] != "running":
            return job
        assert time.monotonic() < deadline, job
        time.sleep(0.005)


def test_running_job_survives_completed_history_limit(rpc_module: types.ModuleType) -> None:
    rpc = rpc_module.FreeCADRPC()
    release = threading.Event()
    rpc_module.FreeCAD.test_release = release
    first = rpc.execute_code_async("FreeCAD.test_release.wait(5)")["job_id"]
    try:
        completed = []
        for _ in range(21):
            job_id = f"completed-{len(completed)}"
            rpc_module._record_job(job_id, state="done")
            completed.append(job_id)
        assert rpc.get_async_status(first)["job"]["state"] == "running"
        assert rpc.get_rpc_status()["async_jobs_running"] == [first]
        assert rpc.get_async_status(completed[0])["success"] is False
        assert len(rpc.get_async_status()["jobs"]) == 21  # 20 finished plus the active job.
    finally:
        release.set()
    assert wait_for_job(rpc, first)["state"] == "done"
    assert len(rpc.get_async_status()["jobs"]) == 20
    # The oldest-started job just finished; completion order retains it.
    assert rpc.get_async_status(first)["success"] is True


def test_concurrent_script_admission_has_exactly_one_owner(
    rpc_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch,
) -> None:
    rpc = rpc_module.FreeCADRPC()
    release = threading.Event()
    rpc_module.FreeCAD.test_release = release
    monkeypatch.setattr(rpc_module, "time", types.SimpleNamespace(time=lambda: 123456.0))
    # This case exercises job creation concurrency, independently of Qt wakeup.
    monkeypatch.setattr(rpc_module, "dispatch_to_gui", lambda task, **_: task())
    try:
        with ThreadPoolExecutor(max_workers=8) as callers:
            results = list(callers.map(lambda _: rpc.execute_code_async("FreeCAD.test_release.wait(5)"), range(32)))
        ids = [result["job_id"] for result in results if result["success"]]
        assert len(ids) == 1
        assert all(result.get("code") == "SCRIPT_BUSY" for result in results if not result["success"])
        assert set(rpc.get_rpc_status()["async_jobs_running"]) == set(ids)
    finally:
        release.set()


@pytest.mark.parametrize("error", ["SystemExit(2)", "KeyboardInterrupt()", "ValueError('failure')"])
def test_worker_exits_are_reported_as_failed_jobs(rpc_module: types.ModuleType, error: str) -> None:
    rpc = rpc_module.FreeCADRPC()
    job_id = rpc.execute_code_async(f"raise {error}")["job_id"]
    job = wait_for_job(rpc, job_id)
    assert job["state"] == "failed"
    assert job["error"].startswith(error.split("(")[0])
    assert "Traceback" in job["traceback"]
    assert "finished" in job


def test_thread_start_failure_does_not_leave_a_running_job(
    rpc_module: types.ModuleType, monkeypatch: pytest.MonkeyPatch,
) -> None:
    def cannot_start(**_kwargs):
        raise RuntimeError("cannot start new thread")
    monkeypatch.setattr(rpc_module, "threading", types.SimpleNamespace(Thread=cannot_start))
    rpc = rpc_module.FreeCADRPC()
    result = rpc.execute_code_async("pass")
    assert result["success"] is False
    assert wait_for_job(rpc, result["job_id"])["state"] == "failed"
    assert rpc.get_rpc_status()["async_jobs_running"] == []


def test_job_result_is_available_while_cleanup_is_blocked(rpc_module: types.ModuleType) -> None:
    rpc = rpc_module.FreeCADRPC()
    release = threading.Event()
    rpc_module.FreeCAD.test_release = release
    busy = threading.Thread(
        target=lambda: rpc_module.test_dispatch.dispatch_to_gui(lambda: release.wait(5), timeout=10, operation_name="typed_operation"), daemon=True,
    )
    busy.start()
    try:
        deadline = time.monotonic() + 2
        while rpc.get_rpc_status()["gui_dispatch"]["state"] != "busy":
            assert time.monotonic() < deadline
            time.sleep(0.005)
        # The status-bar updates queue behind the busy GUI task; the job's
        # result must not wait for them.
        job_id = rpc.execute_code_async("raise ValueError('failed before cleanup')")["job_id"]
        assert wait_for_job(rpc, job_id)["state"] == "failed"
        assert rpc.get_rpc_status()["async_jobs_running"] == []
    finally:
        release.set()
        busy.join(timeout=5)


def test_status_message_is_cleared_after_a_job_that_ran_behind_a_busy_gui(
    rpc_module: types.ModuleType,
) -> None:
    status_bar = rpc_module.FreeCADGui.getMainWindow().statusBar()
    rpc = rpc_module.FreeCADRPC()
    release = threading.Event()
    rpc_module.FreeCAD.test_release = release
    busy = threading.Thread(
        target=lambda: rpc_module.test_dispatch.dispatch_to_gui(lambda: release.wait(5), timeout=10, operation_name="typed_operation"), daemon=True,
    )
    busy.start()
    deadline = time.monotonic() + 2
    while rpc.get_rpc_status()["gui_dispatch"]["state"] != "busy":
        assert time.monotonic() < deadline
        time.sleep(0.005)
    job_id = rpc.execute_code_async("pass")["job_id"]
    assert wait_for_job(rpc, job_id)["state"] == "done"
    release.set()
    busy.join(timeout=5)
    rpc_module.test_dispatch.process_gui_tasks()
    assert status_bar.currentMessage() == ""


def test_scripts_and_job_queries_do_not_scan_unrelated_documents(rpc_module: types.ModuleType) -> None:
    def unexpected_scan():
        raise AssertionError("unrelated document must not be inspected")

    rpc_module.FreeCAD.listDocuments = unexpected_scan
    rpc = rpc_module.FreeCADRPC()
    assert rpc.execute_code("value = 42")["success"] is True
    job_id = rpc.execute_code_async("value += 1")["job_id"]
    assert wait_for_job(rpc, job_id)["state"] == "done"
    assert rpc.execute_code("print(value)")["message"].endswith("43\n")


def test_async_start_does_not_wait_for_a_busy_gui_thread(rpc_module: types.ModuleType) -> None:
    rpc = rpc_module.FreeCADRPC()
    release = threading.Event()
    rpc_module.FreeCAD.test_release = release
    busy = threading.Thread(
        target=lambda: rpc_module.test_dispatch.dispatch_to_gui(lambda: release.wait(5), timeout=10, operation_name="typed_operation"), daemon=True,
    )
    busy.start()
    try:
        deadline = time.monotonic() + 2
        while rpc.get_rpc_status()["gui_dispatch"]["state"] != "busy":
            assert time.monotonic() < deadline
            time.sleep(0.005)
        before = time.monotonic()
        job_id = rpc.execute_code_async("pass")["job_id"]
        assert time.monotonic() - before < 0.5
        assert wait_for_job(rpc, job_id)["state"] == "done"
    finally:
        release.set()
        busy.join(timeout=5)
