import functools
import logging
import xmlrpc.client
from contextlib import asynccontextmanager
from typing import Annotated, Any, AsyncIterator, Callable, Dict, Literal

import anyio
from pydantic import Field

try:
    # mcp 1.x
    from mcp.server.fastmcp import Context, FastMCP
except ImportError:
    # mcp 2.x moved mcp.server.fastmcp to mcp.server.mcpserver and renamed
    # FastMCP to MCPServer; the API surface used here is unchanged.
    from mcp.server.mcpserver import Context
    from mcp.server.mcpserver import MCPServer as FastMCP
from mcp.types import CallToolResult, ImageContent, TextContent

from .freecad_client import FreeCADConnection
from .http_transport import (
    DEFAULT_LISTEN_HOST,
    DEFAULT_LISTEN_PORT,
    UnsafeListenConfigError,
    parse_listen_host,
    parse_listen_port,
    run_http,
    validate_listen_config,
)
from .operations import (
    create_document_operation,
    create_object_operation,
    delete_object_operation,
    edit_object_operation,
    execute_code_async_operation,
    execute_code_headless_operation,
    execute_code_operation,
    get_object_operation,
    get_objects_operation,
    get_parts_list_operation,
    get_async_status_operation,
    get_task_status_operation,
    get_rpc_status_operation,
    get_view_operation,
    insert_part_from_library_operation,
    list_documents_operation,
    reload_document_operation,
    run_fem_analysis_operation,
)
from .prompt_text import ASSET_CREATION_STRATEGY
from .responses import ErrorResponse, ToolResponse
from .server_state import ServerState


logging.basicConfig(
    level=logging.WARNING, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("FreeCADMCPserver")
logger.setLevel(logging.INFO)

ViewName = Literal[
    "Isometric", "Front", "Top", "Right", "Back", "Left", "Bottom", "Dimetric", "Trimetric"
]
PositiveTimeout = Annotated[float, Field(strict=True, gt=0, allow_inf_nan=False)]
FemTimeout = Annotated[int, Field(strict=True, gt=0, le=2**31 - 1)]

state = ServerState()


@asynccontextmanager
async def server_lifespan(server: FastMCP) -> AsyncIterator[Dict[str, Any]]:
    try:
        logger.info("FreeCADMCP server starting up")
        try:
            await anyio.to_thread.run_sync(get_freecad_connection)
            logger.info("Successfully connected to FreeCAD on startup")
        except Exception as e:
            logger.warning(f"Could not connect to FreeCAD on startup: {str(e)}")
            logger.warning(
                "Make sure the FreeCAD addon is running before using FreeCAD resources or tools"
            )
        yield {}
    finally:
        if state.freecad_connection:
            logger.info("Disconnecting from FreeCAD on shutdown")
            state.freecad_connection.disconnect()
            state.freecad_connection = None
        logger.info("FreeCADMCP server shut down")


mcp = FastMCP(
    "FreeCADMCP",
    instructions="FreeCAD integration through the Model Context Protocol",
    lifespan=server_lifespan,
)


def tool(fn: Callable[..., ToolResponse]) -> Callable[..., ToolResponse | CallToolResult]:
    """Register ``fn`` as a tool whose next reply carries a pending version warning.

    A failure returned as an ``ErrorResponse`` is sent with ``isError`` set.
    """

    @functools.wraps(fn)
    def wrapper(*args: Any, **kwargs: Any) -> ToolResponse | CallToolResult:
        response = fn(*args, **kwargs)
        is_error = isinstance(response, ErrorResponse)
        with state.lock:
            notice, state.version_notice = state.version_notice, None
        if notice:
            response = [TextContent(type="text", text=f"Warning: {notice}"), *response]
        if is_error:
            return CallToolResult(content=list(response), isError=True)
        return response

    @functools.wraps(fn)
    async def async_wrapper(*args: Any, **kwargs: Any) -> ToolResponse | CallToolResult:
        # SDK 1.x invokes synchronous tools on its event loop. Explicitly
        # offload on both SDK versions so status and cancellation stay usable.
        return await anyio.to_thread.run_sync(functools.partial(wrapper, *args, **kwargs))

    mcp.tool(structured_output=False)(async_wrapper)
    return wrapper


def get_freecad_connection() -> FreeCADConnection:
    with state.lock:
        return _get_freecad_connection_locked()


def _get_freecad_connection_locked() -> FreeCADConnection:
    """Get or create a persistent FreeCAD connection.

    The connection is cached only after FreeCAD answers, so a server started
    before FreeCAD checks the addon version on the first call that reaches it.
    """
    if state.freecad_connection is None:
        connection = FreeCADConnection(
            host=state.rpc_host, port=9875, token=state.auth_token
        )
        try:
            # ping() raises, rather than returning False, when nothing listens.
            reachable = connection.ping()
        except Exception as e:
            connection.disconnect()
            if isinstance(e, xmlrpc.client.ProtocolError) and e.errcode == 401:
                raise Exception(
                    "FreeCAD rejected the connection: the addon requires an auth "
                    "token, and none or a different one was given. Pass the token "
                    "set with 'Set Auth Token' in FreeCAD through the "
                    "FREECAD_MCP_TOKEN environment variable or --auth-token."
                ) from e
            raise Exception(
                f"Failed to connect to FreeCAD ({e}). Make sure the FreeCAD addon is running."
            ) from e
        if not reachable:
            logger.error("Failed to ping FreeCAD")
            connection.disconnect()
            raise Exception(
                "Failed to connect to FreeCAD. Make sure the FreeCAD addon is running."
            )
        state.freecad_connection = connection
    notice = state.freecad_connection.check_addon_version()
    if notice != state.last_version_notice:
        state.version_notice = notice
        state.last_version_notice = notice
        if notice:
            logger.warning(notice)
    return state.freecad_connection


@tool
def create_document(ctx: Context, name: str) -> list[TextContent]:
    """Create a new document in FreeCAD.

    Args:
        name: The name of the document to create.

    Returns:
        A message indicating the success or failure of the document creation.

    Examples:
        If you want to create a document named "MyDocument", you can use the following data.
        ```json
        {
            "name": "MyDocument"
        }
        ```
    """
    return create_document_operation(get_freecad_connection(), name)


@tool
def create_object(
    ctx: Context,
    doc_name: str,
    obj_type: str,
    obj_name: str,
    analysis_name: str | None = None,
    obj_properties: dict[str, Any] | None = None,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Create a new object in FreeCAD.

    ``obj_type`` must name a type registered in FreeCAD's C++ type system, such
    as "Part::", "PartDesign::" or "Fem::" types. A number of FreeCAD features
    are implemented in Python rather than C++ and so are not registered types;
    of those, these are supported here through dedicated factories. They accept
    the properties listed beside them (required for Draft factories):

        Part::Tube        InnerRadius, OuterRadius, Height (optional; defaults 2, 5, 10 mm)
        Draft::Circle     Radius
        Draft::Rectangle  Length, Height
        Draft::Polygon    FacesNumber, Radius
        Draft::Wire       Points (list of {x, y, z}), optional Closed

    Any other Python-implemented type (Draft::Point, Draft::Ellipse, ...) must
    be built with ``execute_code`` instead.

    Note that the Draft factories name objects themselves, so for those the
    returned object_name will differ from the requested obj_name, which is
    applied to the object's Label instead. Always use the returned name in
    later get_object/edit_object calls.

    Args:
        doc_name: The name of the document to create the object in.
        obj_type: The type of the object to create (e.g. 'Part::Box', 'Part::Cylinder', 'Part::Cut', 'PartDesign::Body', etc.).
        obj_name: The name of the object to create.
        obj_properties: The properties of the object to create.
        include_screenshot: Whether to return a screenshot of the model (default True).
            Set to False to save tokens when visual feedback is not needed,
            e.g. for intermediate steps in a longer sequence of changes.
        view_name: The view orientation of the returned screenshot (default "Isometric").
            Pick the view that best shows the change being made.

    Returns:
        A message indicating the success or failure of the object creation and a screenshot of the object.

    Examples:
        If you want to create a cylinder with a height of 30 and a radius of 10, you can use the following data.
        ```json
        {
            "doc_name": "MyCylinder",
            "obj_name": "Cylinder",
            "obj_type": "Part::Cylinder",
            "obj_properties": {
                "Height": 30,
                "Radius": 10,
                "Placement": {
                    "Base": {
                        "x": 10,
                        "y": 10,
                        "z": 0
                    },
                    "Rotation": {
                        "Axis": {
                            "x": 0,
                            "y": 0,
                            "z": 1
                        },
                        "Angle": 45
                    }
                },
                "ViewObject": {
                    "ShapeColor": [0.5, 0.5, 0.5, 1.0]
                }
            }
        }
        ```

        If you want to cut one solid out of another, create both solids first,
        then reference them by name as 'Base' and 'Tool'.
        ```json
        {
            "doc_name": "MyPart",
            "obj_name": "Cut",
            "obj_type": "Part::Cut",
            "obj_properties": {
                "Base": "Box",
                "Tool": "Cylinder"
            }
        }
        ```

        If you want to create a pipe with an outer diameter of 250, a 10 wall
        and a length of 500, you can use the following data.
        ```json
        {
            "doc_name": "MyPipe",
            "obj_name": "Pipe",
            "obj_type": "Part::Tube",
            "obj_properties": {
                "OuterRadius": 125,
                "InnerRadius": 115,
                "Height": 500
            }
        }
        ```

        If you want to create a FEM analysis, you can use the following data.
        ```json
        {
            "doc_name": "MyFEMAnalysis",
            "obj_name": "FemAnalysis",
            "obj_type": "Fem::AnalysisPython"
        }
        ```

        If you want to create a FEM constraint, you can use the following data.
        ```json
        {
            "doc_name": "MyFEMAnalysis",
            "obj_name": "FemConstraint",
            "obj_type": "Fem::ConstraintFixed",
            "analysis_name": "FemAnalysis",
            "obj_properties": {
                "References": [
                    {
                        "object_name": "MyObject",
                        "face": "Face1"
                    }
                ]
            }
        }
        ```

        If you want to create a FEM mechanical material, you can use the following data.
        ```json
        {
            "doc_name": "MyFEMAnalysis",
            "obj_name": "FemMechanicalMaterial",
            "obj_type": "Fem::MaterialCommon",
            "analysis_name": "FemAnalysis",
            "obj_properties": {
                "Material": {
                    "Name": "MyMaterial",
                    "Density": "7900 kg/m^3",
                    "YoungsModulus": "210 GPa",
                    "PoissonRatio": "0.3"
                }
            }
        }
        ```

        If you want to create a FEM mesh, you can use the following data.
        The `Shape` property is required (legacy `Part` is also accepted).
        On FreeCAD 1.x the size limits are `CharacteristicLengthMax/Min`;
        the legacy `ElementSizeMax/Min` keys are also accepted.
        ```json
        {
            "doc_name": "MyFEMAnalysis",
            "obj_name": "FemMesh",
            "obj_type": "Fem::FemMeshGmsh",
            "analysis_name": "FemAnalysis",
            "obj_properties": {
                "Shape": "MyObject",
                "CharacteristicLengthMax": 10,
                "CharacteristicLengthMin": 0.1
            }
        }
        ```
    """
    return create_object_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        doc_name,
        obj_type,
        obj_name,
        analysis_name,
        obj_properties,
        include_screenshot,
        view_name,
    )


@tool
def edit_object(
    ctx: Context,
    doc_name: str,
    obj_name: str,
    obj_properties: dict[str, Any],
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Edit an object in FreeCAD.
    This tool is used when the `create_object` tool cannot handle the object creation.

    Args:
        doc_name: The name of the document to edit the object in.
        obj_name: The name of the object to edit.
        obj_properties: The properties of the object to edit.
        include_screenshot: Whether to return a screenshot of the model (default True).
            Set to False to save tokens when visual feedback is not needed,
            e.g. for intermediate steps in a longer sequence of changes.
        view_name: The view orientation of the returned screenshot (default "Isometric").
            Pick the view that best shows the change being made.

    Returns:
        A message indicating the success or failure of the object editing and a screenshot of the object.
    """
    return edit_object_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        doc_name,
        obj_name,
        obj_properties,
        include_screenshot,
        view_name,
    )


@tool
def delete_object(
    ctx: Context,
    doc_name: str,
    obj_name: str,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Delete an object in FreeCAD.

    Args:
        doc_name: The name of the document to delete the object from.
        obj_name: The name of the object to delete.
        include_screenshot: Whether to return a screenshot of the model (default True).
            Set to False to save tokens when visual feedback is not needed,
            e.g. for intermediate steps in a longer sequence of changes.
        view_name: The view orientation of the returned screenshot (default "Isometric").
            Pick the view that best shows the change being made.

    Returns:
        A message indicating the success or failure of the object deletion and a screenshot of the object.
    """
    return delete_object_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        doc_name,
        obj_name,
        include_screenshot,
        view_name,
    )


@tool
def execute_code_async(ctx: Context, code: str) -> list[TextContent]:
    """Execute Python code in FreeCAD without waiting for completion.

    Use this ONLY for long-running background computations that do NOT touch the
    FreeCAD GUI or mutate the FreeCAD document tree directly.

    This tool runs the submitted code in a background thread and returns
    immediately. Because it does not run on FreeCAD's main GUI thread, the code
    must NOT directly call FreeCADGui APIs, manipulate the active view or
    selection, create or edit document objects, change object properties, call
    doc.recompute(), or save documents. FreeCAD documents and the Coin3D
    scenegraph are not thread-safe: writing to them from this thread races the
    GUI thread and can wedge FreeCAD's event loop, after which the RPC server
    stops responding entirely and FreeCAD must be restarted.

    Every document or view write must instead be handed to the GUI thread through
    the injected commit() helper:

        commit(fn, timeout=120) -> fn's return value

    Scripts share a live namespace. Saved functions can use commit() in later
    async calls; calling it from execute_code or a GUI callback raises immediately.
    Only one shared-namespace script is admitted at a time. Overlapping scripts
    return SCRIPT_BUSY without starting; status and document tools remain usable.

    commit() queues fn on the GUI thread, waits for it, and raises RuntimeError if
    dispatch fails or times out. Example:

        fused = base.fuse(addition).removeSplitter()   # slow, safe in background

        def apply():                                   # runs on the GUI thread
            obj.Shape = fused
            doc.recompute()

        commit(apply)

    For code that is not dominated by heavy geometry computation, use execute_code
    instead. execute_code runs entirely on the FreeCAD GUI thread and is the safe
    default for normal FreeCAD automation.

    Use execute_code_async only when the heavy part is long-running OCCT geometry
    (e.g. fuse/cut/loft on already-fetched shapes) or other CPU-bound computation
    that would exceed execute_code's 90 s GUI-thread budget.

    Typical usage pattern:
    1. Fetch shapes into module-level variables first (via execute_code).
    2. Run the heavy computation via execute_code_async.
    3. Apply the result inside commit(), or store it in a module-level Python
       variable (not in the FreeCAD document) for a later execute_code call.

    Performance note: boolean operations against shapes with many faces (e.g. a
    ribbed lid) are expensive. Fuse the additions together first, then apply a
    single boolean against the heavy shape, and avoid doc.recompute() unless the
    dependency graph really needs it.

    Args:
        code: Background-safe Python code to execute. Use commit(fn) for all
            document and view writes.

    Returns:
        A message with the job_id of the started background execution.
    """
    return execute_code_async_operation(get_freecad_connection(), code)


@tool
def execute_code_headless(ctx: Context, code: str, timeout: PositiveTimeout = 600) -> list[TextContent]:
    """Run a FreeCAD Python script in a separate headless `freecadcmd` process.

    Use this for OCCT work that can crash or block FreeCAD: helical threads
    (makeHelix + makePipeShell), lofts and sweeps, booleans with many or
    B-spline tools, long parametric rebuilds. A native OpenCascade crash
    here only kills the helper process; the GUI and its open documents
    survive, and the tool reports the crash signal and the script's output.

    The script runs on the MCP server machine, independently of --host, in a
    fresh process without GUI: import FreeCAD/Part
    yourself, open documents from disk (FreeCAD.openDocument(path)), save
    results with doc.save()/saveAs() or Shape.exportBrep(). Nothing from the
    execute_code namespace is available. Print progress to stdout; it is
    returned when the process ends. After the script saved a .FCStd that is
    open in the GUI, call reload_document(doc_name) to show the result.

    Args:
        code: Complete Python script for freecadcmd.
        timeout: Positive finite seconds to wait before killing the process
            (default 600). Partial output is preserved on timeout.

    Returns:
        Exit status, crash/timeout diagnosis and the script's printed output.
    """
    return execute_code_headless_operation(state.freecadcmd, code, timeout)


@tool
def get_task_status(ctx: Context, task_id: str | None = None) -> list[TextContent]:
    """Poll a timed-out GUI operation without waiting for the GUI thread.

    Omit task_id to list pending work and the last 20 completed operations.
    A timed_out_running task can still mutate the document. Wait for its final
    result before retrying. History is in-memory and resets when FreeCAD exits;
    large result previews are capped at 65,536 serialized characters and marked
    result_truncated.
    """
    return get_task_status_operation(get_freecad_connection(), task_id)


@tool
def get_async_status(ctx: Context, job_id: str = "") -> list[TextContent]:
    """Report the state of background jobs started by execute_code_async.

    Does not use the FreeCAD GUI thread, so it answers even while a job runs.

    Args:
        job_id: The id returned by execute_code_async. Empty lists all running
            jobs and up to 20 recently completed jobs.

    Returns:
        For one job: its state (running/done/failed), the error and traceback
        when it failed. History is held in memory until FreeCAD exits.
    """
    return get_async_status_operation(get_freecad_connection(), job_id)


@tool
def execute_code(
    ctx: Context,
    code: str,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
    timeout: PositiveTimeout | None = None,
) -> list[TextContent | ImageContent]:
    """Execute arbitrary Python code in FreeCAD.

    Args:
        code: The Python code to execute.
        include_screenshot: Whether to return a screenshot of the model (default True).
            Set to False to save tokens when the code does not change the model's
            appearance, e.g. analytical or computational scripts whose result is
            printed output, or intermediate steps in a longer sequence of changes.
        view_name: The view orientation of the returned screenshot (default "Isometric").
            Pick the view that best shows the change being made.
        timeout: Positive finite seconds for each of the queue and GUI execution
            budgets, overriding the 90 s default for this call (capped at 1800).
            Raise it for slow work that must
            run on the GUI thread, such as importing or exporting a large STEP
            assembly. Without it the call reports a timeout while the task keeps
            running; poll get_task_status using the returned task_id for the late result. Prefer
            execute_code_async for heavy pure-geometry work that touches neither
            the document nor the GUI.

    Returns:
        A message indicating the success or failure of the code execution, the output of the code execution, and a screenshot of the object.
    """
    return execute_code_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        code,
        include_screenshot,
        view_name,
        timeout,
    )


@tool
def get_view(
    ctx: Context,
    view_name: ViewName,
    width: int | None = None,
    height: int | None = None,
    focus_object: str | None = None,
) -> list[ImageContent | TextContent]:
    """Get a screenshot of the active view.

    Args:
        view_name: The name of the view to get the screenshot of.
        The following views are available:
        - "Isometric"
        - "Front"
        - "Top"
        - "Right"
        - "Back"
        - "Left"
        - "Bottom"
        - "Dimetric"
        - "Trimetric"
        width: Requested width in pixels. With both dimensions omitted, the
            viewport is scaled to a maximum edge of 1024 pixels. If only one
            dimension is omitted, that dimension uses the viewport size.
        height: Requested height in pixels, following the same sizing rules.
        focus_object: The name of the object to focus on. If not specified, fits all objects in the view.

    Returns:
        A screenshot of the active view.
    """
    return get_view_operation(get_freecad_connection(), view_name, width, height, focus_object)


@tool
def insert_part_from_library(
    ctx: Context,
    relative_path: str,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Insert a part from the parts library addon.

    Args:
        relative_path: The relative path of the part to insert.
        include_screenshot: Whether to return a screenshot of the model (default True).
            Set to False to save tokens when visual feedback is not needed,
            e.g. for intermediate steps in a longer sequence of changes.
        view_name: The view orientation of the returned screenshot (default "Isometric").
            Pick the view that best shows the change being made.

    Returns:
        A message indicating the success or failure of the part insertion and a screenshot of the object.
    """
    return insert_part_from_library_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        relative_path,
        include_screenshot,
        view_name,
    )


@tool
def get_objects(
    ctx: Context,
    doc_name: str,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Get all objects in a document.
    You can use this tool to get the objects in a document to see what you can check or edit.

    Args:
        doc_name: The name of the document to get the objects from.
        include_screenshot: Whether to return a screenshot of the document (default True).
            Set to False to save tokens when only the object data is needed.
        view_name: The view orientation of the returned screenshot (default "Isometric").

    Returns:
        A list of objects in the document and a screenshot of the document.
    """
    return get_objects_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        doc_name,
        include_screenshot,
        view_name,
    )


@tool
def get_object(
    ctx: Context,
    doc_name: str,
    obj_name: str,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Get an object from a document.
    You can use this tool to get the properties of an object to see what you can check or edit.

    Args:
        doc_name: The name of the document to get the object from.
        obj_name: The name of the object to get.
        include_screenshot: Whether to return a screenshot of the document (default True).
            Set to False to save tokens when only the object data is needed.
        view_name: The view orientation of the returned screenshot (default "Isometric").

    Returns:
        The object and a screenshot of the object.
    """
    return get_object_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        doc_name,
        obj_name,
        include_screenshot,
        view_name,
    )


@tool
def get_parts_list(ctx: Context) -> list[TextContent]:
    """Get the list of parts in the parts library addon.
    """
    return get_parts_list_operation(get_freecad_connection())


@tool
def reload_document(ctx: Context, doc_name: str) -> list[TextContent]:
    """Close and re-open a document to pick up external file changes.

    Use this AFTER the document's .FCStd file has been modified by
    something outside of FreeCAD's GUI process — for example, a
    headless `freecadcmd` script that edited and saved the file. The
    open GUI document is otherwise unaware of on-disk changes; this
    tool closes the stale in-memory copy and reopens the file from
    disk so the GUI shows current geometry.

    Args:
        doc_name: The name of the open document to reload. Must match
            the name shown by ``list_documents``.

    Returns:
        A message confirming the document was reloaded, or describing
        the failure (document not loaded, no associated file, etc).
        FreeCAD names the reopened document after the file stem, which
        can differ from ``doc_name`` ("HandleConcept3D" saved as
        handle-concept-3d.FCStd reopens as handle_concept_3d); the reply
        names the document you should use from then on.

    Examples:
        ```json
        {
            "doc_name": "chassis"
        }
        ```
    """
    return reload_document_operation(get_freecad_connection(), doc_name)


@tool
def list_documents(ctx: Context) -> list[TextContent]:
    """Get the list of open documents in FreeCAD.

    Returns:
        A list of document names.
    """
    return list_documents_operation(get_freecad_connection())


@tool
def get_rpc_status(ctx: Context) -> list[TextContent]:
    """Get RPC and FreeCAD GUI-dispatch health.

    This tool does not use FreeCAD's GUI thread, so it remains available after
    a GUI operation times out. A ``stuck`` state identifies the operation that
    is still running and indicates that FreeCAD may need to be restarted.
    ``version_check`` is "ok" or says whether the addon or the server needs
    updating.
    """
    return get_rpc_status_operation(get_freecad_connection())


@tool
def run_fem_analysis(
    ctx: Context,
    doc_name: str,
    analysis_name: str,
    timeout: FemTimeout = 600,
    include_screenshot: bool = True,
    view_name: ViewName = "Isometric",
) -> list[TextContent | ImageContent]:
    """Run the CalculiX solver on an existing Fem::FemAnalysis container and return summary results.

    Prerequisites in the document, all created with `create_object`:
    - A Part-derived solid (e.g. Part::Box, PartDesign::Body) acting as the geometry.
    - A Fem::AnalysisPython container.
    - A material: type "Fem::MaterialCommon" with analysis_name set (built with
      ObjectsFem.makeMaterialSolid) and its Material given as a dict with units,
      e.g. {"Name": "Steel", "YoungsModulus": "210 GPa", "PoissonRatio": "0.3",
      "Density": "7900 kg/m^3"}. A dict read from the material library can
      come back empty; give the values.
    - A mesh: type "Fem::FemMeshGmsh" with analysis_name, Shape (the geometry)
      and CharacteristicLengthMax / CharacteristicLengthMin; it is generated
      when created. A section needs several elements across its thickness,
      or bending stress comes out far too low.
    - At least one Fem::ConstraintFixed and one Fem::ConstraintForce (or
      ConstraintPressure) whose References are faces of the geometry.
    - Set Force with its unit, e.g. "1000 N": create_object/edit_object reject
      unitless values. In existing documents and execute_code, a plain number
      uses millinewtons, so Force = 1000 applies 1 N. The force acts along the
      normal of the loaded face unless Direction links an edge or face;
      Reversed flips it.

    A SolverCcxTools is auto-created if the analysis has none. The reply
    lists mechanical loads captured in the same GUI operation as the solve
    (in N and MPa, with faces and direction). A failed load read stops the solve.
    Direction can be set to {"object_name": "Beam", "edge": "Edge1"}.

    The solver runs synchronously on the FreeCAD GUI thread. Other document
    operations queue behind it; get_rpc_status and get_async_status remain available.

    Returns max von Mises stress (MPa), max/min displacement (mm), node count,
    and the working directory CalculiX wrote to. On failure, returns the
    prerequisite-check or solver error along with the working directory for
    triage.

    Args:
        doc_name: Name of the FreeCAD document.
        analysis_name: Name of the Fem::AnalysisPython object.
        timeout: Seconds to wait for the solver (default 600).
        include_screenshot: Whether to return a screenshot of the model (default True).
            Set to False to save tokens when only the numeric results are needed.
        view_name: The view orientation of the returned screenshot (default "Isometric").
    """
    return run_fem_analysis_operation(
        get_freecad_connection(),
        state.only_text_feedback,
        doc_name,
        analysis_name,
        timeout,
        include_screenshot,
        view_name,
    )


@mcp.prompt()
def asset_creation_strategy() -> str:
    return ASSET_CREATION_STRATEGY


def _validate_host(value: str) -> str:
    """Validate that *value* is a valid IP address or hostname.

    Used as the ``type`` callback for the ``--host`` argparse argument.
    Raises ``argparse.ArgumentTypeError`` on invalid input.
    """
    import argparse

    import validators

    if validators.ipv6(value):
        raise argparse.ArgumentTypeError("IPv6 is not supported by the addon listener; use IPv4 or a hostname resolving to IPv4")
    if validators.ipv4(value) or validators.hostname(value):
        return value
    raise argparse.ArgumentTypeError(
        f"Invalid host: '{value}'. Must be a valid IPv4 address or hostname."
    )


def main():
    """Run the MCP server"""
    import argparse
    import os

    parser = argparse.ArgumentParser()
    parser.add_argument("--only-text-feedback", action="store_true", help="Only return text feedback")
    parser.add_argument("--host", type=_validate_host, default="localhost", help="Host address of the FreeCAD RPC server to connect to (default: localhost)")
    parser.add_argument(
        "--auth-token",
        default=None,
        help="Auth token the FreeCAD RPC server requires (falls back to the "
        "FREECAD_MCP_TOKEN environment variable, which is preferable because "
        "other users can read command-line arguments; omit if the addon has "
        "no token set)",
    )
    parser.add_argument("--freecadcmd", default=None, help="Command that starts headless FreeCAD for execute_code_headless, e.g. 'flatpak run --command=freecadcmd org.freecad.FreeCAD' (default: auto-detect PATH, then Flatpak)")
    parser.add_argument(
        "--transport",
        choices=["stdio", "streamable-http", "sse"],
        default="stdio",
        help="How MCP clients connect to this server (default: stdio). HTTP modes "
        "listen on loopback only unless --listen-host says otherwise.",
    )
    parser.add_argument("--listen-host", type=parse_listen_host, default=None, help=f"Address to listen on for HTTP transports (default: {DEFAULT_LISTEN_HOST}). A non-loopback address requires a listen token.")
    parser.add_argument("--listen-port", type=parse_listen_port, default=None, help=f"Port to listen on for HTTP transports (default: {DEFAULT_LISTEN_PORT})")
    parser.add_argument(
        "--listen-token",
        default=None,
        help="Bearer token HTTP clients must send (falls back to the "
        "FREECAD_MCP_LISTEN_TOKEN environment variable, which is preferable "
        "because other users can read command-line arguments). Required when "
        "listening on a non-loopback address.",
    )
    parser.add_argument(
        "--allowed-host",
        action="append",
        default=[],
        metavar="HOST[:PORT]",
        help="Extra Host header value to accept for HTTP transports (repeatable). "
        "Loopback names are always accepted.",
    )
    parser.add_argument(
        "--allow-insecure-remote",
        action="store_true",
        default=os.environ.get("FREECAD_MCP_ALLOW_INSECURE_REMOTE") == "1",
        help="Allow listening on a non-loopback address without a token. Intended "
        "for containers whose published port is restricted to the host's loopback "
        "(-p 127.0.0.1:PORT:PORT). Also enabled by FREECAD_MCP_ALLOW_INSECURE_REMOTE=1.",
    )
    args = parser.parse_args()
    listen_token = args.listen_token or os.environ.get("FREECAD_MCP_LISTEN_TOKEN") or None
    if args.transport == "stdio":
        given = [
            flag
            for flag, value in (
                ("--listen-host", args.listen_host),
                ("--listen-port", args.listen_port),
                ("--listen-token", args.listen_token),
                ("--allowed-host", args.allowed_host),
                ("--allow-insecure-remote", args.allow_insecure_remote),
            )
            if value
        ]
        if given:
            parser.error(f"{', '.join(given)} only apply to --transport streamable-http or sse")
    listen_host = args.listen_host or DEFAULT_LISTEN_HOST
    listen_port = args.listen_port or DEFAULT_LISTEN_PORT
    if args.transport != "stdio":
        try:
            validate_listen_config(listen_host, listen_token, args.allow_insecure_remote)
        except UnsafeListenConfigError as e:
            parser.error(str(e))
    state.only_text_feedback = args.only_text_feedback
    state.rpc_host = args.host
    state.auth_token = args.auth_token or os.environ.get("FREECAD_MCP_TOKEN") or None
    from .headless import parse_command
    state.freecadcmd = parse_command(args.freecadcmd)
    logger.info(f"Only text feedback: {state.only_text_feedback}")
    logger.info(f"Connecting to FreeCAD RPC server at: {state.rpc_host}")
    if state.auth_token:
        logger.info("Auth token configured for RPC connection")
    if args.transport == "stdio":
        mcp.run()
    else:
        run_http(mcp, args.transport, listen_host, listen_port, listen_token, args.allowed_host, args.allow_insecure_remote)
