"""Run a FreeCAD script in a separate ``freecadcmd`` process.

Heavy OCCT work (helical sweeps, lofts, many-tool booleans) can segfault
OpenCascade. Inside the GUI process that kills FreeCAD together with every
unsaved document; here it only kills the helper process, and the caller gets
the exit status and the script's output back.
"""

import logging
import math
import os
import re
import shlex
import shutil
import signal
import subprocess
import tempfile
from pathlib import Path
from typing import Any

logger = logging.getLogger("FreeCADMCPserver")

FLATPAK_APP = "org.freecad.FreeCAD"


def detect_freecadcmd() -> list[str] | None:
    """Find a headless FreeCAD executable: PATH first, then the Flatpak."""
    for name in ("freecadcmd", "FreeCADCmd", "freecadcmd.exe", "freecad.cmd"):
        path = shutil.which(name)
        if path:
            return [path]
    flatpak = shutil.which("flatpak")
    if flatpak:
        try:
            probe = subprocess.run(
                [flatpak, "info", FLATPAK_APP], capture_output=True, timeout=30
            )
        except (OSError, subprocess.TimeoutExpired):
            return None
        if probe.returncode == 0:
            return [flatpak, "run", f"--command=freecadcmd", FLATPAK_APP]
    return None


def parse_command(value: str | None) -> list[str] | None:
    if not value:
        return None
    # --freecadcmd can be an executable path already passed as one CLI argument.
    # Shell splitting would consume Windows backslashes and split its spaces.
    try:
        if Path(value).is_file():
            return [value]
    except OSError:
        # A command line can be an invalid/overlong filename on some platforms.
        pass
    return shlex.split(value)


def _script_dir() -> Path:
    # Flatpak sandboxes usually see $HOME but not /tmp, so keep scripts under HOME.
    d = Path.home() / ".cache" / "freecad-mcp" / "headless"
    d.mkdir(parents=True, exist_ok=True)
    return d


def _clean(output: str | bytes | None) -> str:
    # TimeoutExpired retains captured bytes even when run(text=True) is used.
    # A timeout can also cut a multibyte character in half.
    if output is None:
        return ""
    if isinstance(output, bytes):
        output = output.decode("utf-8", errors="replace")
    return output.rstrip("\r\n")


def _terminate_process_tree(proc: subprocess.Popen) -> None:
    """Stop this invocation's process group/tree, including ordinary children."""
    if os.name == "nt":
        # Windows has no killpg. taskkill /T includes descendants of this PID.
        killed = subprocess.run(
            ["taskkill", "/PID", str(proc.pid), "/T", "/F"],
            capture_output=True, timeout=10,
        )
        if killed.returncode and proc.poll() is None:
            raise OSError("taskkill could not terminate the headless process tree")
    else:
        try:
            os.killpg(proc.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
    if proc.poll() is None:
        proc.kill()


def _run_process(argv: list[str], timeout: float) -> subprocess.CompletedProcess:
    with subprocess.Popen(
        argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,
        text=True, encoding="utf-8", errors="replace", start_new_session=os.name != "nt",
    ) as proc:
        try:
            stdout, stderr = proc.communicate(timeout=timeout)
        except subprocess.TimeoutExpired as exc:
            cleanup_note = ""
            try:
                _terminate_process_tree(proc)
            except (OSError, subprocess.TimeoutExpired) as cleanup_error:
                logger.warning("Headless process tree cleanup failed: %s", cleanup_error)
                cleanup_note = f"\nProcess tree cleanup failed: {cleanup_error}"
                if proc.poll() is None:
                    proc.kill()
            try:
                stdout, stderr = proc.communicate(timeout=5)
                exc.stdout, exc.stderr = stdout, stderr + cleanup_note
            except subprocess.TimeoutExpired:
                # A child that deliberately detached can retain the pipe. Do
                # not wait indefinitely or imply that arbitrary scripts were undone.
                exc.stderr = _clean(exc.stderr) + cleanup_note + "\nA detached child may still be running."
            raise exc
        except BaseException:
            _terminate_process_tree(proc)
            raise
    return subprocess.CompletedProcess(argv, proc.returncode, stdout, stderr)


def run_headless(code: str, timeout: float, command: list[str] | None) -> dict[str, Any]:
    """Execute ``code`` with ``command -c "exec(open(script).read())"``.

    Returns ``success``, ``returncode``, ``output`` (stdout+stderr), and flags
    ``crashed`` (killed by a signal) / ``timed_out``.
    """
    try:
        valid_timeout = not isinstance(timeout, bool) and math.isfinite(timeout) and timeout > 0
    except (TypeError, ValueError, OverflowError):
        valid_timeout = False
    if not valid_timeout:
        return {"success": False, "mutation_outcome": "not_started", "error": "timeout must be a positive finite number"}
    command = command or detect_freecadcmd()
    if not command:
        return {
            "success": False, "mutation_outcome": "not_started",
            "error": "freecadcmd not found: install FreeCAD, or pass --freecadcmd to freecad-mcp",
        }
    with tempfile.NamedTemporaryFile(
        "w", suffix=".py", dir=_script_dir(), delete=False, encoding="utf-8"
    ) as f:
        f.write(code)
        script = f.name
    # freecadcmd block-buffers stdout into a pipe and does not flush it when the
    # script raises, exits, aborts or is killed; PYTHONUNBUFFERED has no effect.
    # Line buffering keeps everything printed before such an exit.
    # The comprehension keeps the script's namespace free of helper names.
    unbuffer = (
        "[getattr(s, 'reconfigure', lambda **k: None)(line_buffering=True) "
        "for s in (__import__('sys').stdout, __import__('sys').stderr)]; "
    )
    argv = command + ["-c", unbuffer + f"exec(open({script!r}, encoding='utf-8').read())"]
    try:
        proc = _run_process(argv, timeout)
    except subprocess.TimeoutExpired as e:
        out = "\n".join(part for part in (_clean(e.stdout), _clean(e.stderr)) if part)
        return {
            "success": False, "mutation_outcome": "partial_or_unknown",
            "timed_out": True,
            "error": f"headless FreeCAD did not finish within {timeout:g} s",
            "output": out,
        }
    except OSError as e:
        return {"success": False, "mutation_outcome": "not_started", "error": f"could not start headless FreeCAD: {e}"}
    finally:
        try:
            os.unlink(script)
        except OSError:
            pass
    output = "\n".join(part for part in (_clean(proc.stdout), _clean(proc.stderr)) if part)
    result: dict[str, Any] = {
        "success": proc.returncode == 0,
        "mutation_outcome": "completed" if proc.returncode == 0 else "partial_or_unknown",
        "returncode": proc.returncode,
        "output": output,
    }
    if proc.returncode < 0:
        sig = -proc.returncode
        try:
            name = signal.Signals(sig).name
        except ValueError:
            name = str(sig)
        result["crashed"] = True
        result["error"] = f"headless FreeCAD crashed with {name} (OCCT native crash; the GUI is unaffected)"
    elif proc.returncode != 0:
        # FreeCAD's own signal handler can print a native backtrace and exit 1,
        # hiding the signal from the OS exit status. Label this as a report
        # from FreeCAD, distinct from an OS-observed negative return code.
        crash = re.search(r"(?m)^Program received signal (SIG[A-Z0-9]+),", output)
        if crash:
            result["crashed"] = True
            result["error"] = (
                f"headless FreeCAD reported a crash with {crash.group(1)} "
                f"(exit code {proc.returncode}; the GUI is unaffected)"
            )
        else:
            result["error"] = f"script failed (exit code {proc.returncode})"
    return result
