import json
import subprocess
import sys
import time
from pathlib import Path

import pytest

import freecad_mcp.headless as headless

from freecad_mcp.headless import parse_command, run_headless
from freecad_mcp.operations.core import format_headless_result

PY = [sys.executable]  # stands in for freecadcmd: both accept `-c <code>`


@pytest.fixture(autouse=True)
def temporary_scripts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(headless, "_script_dir", lambda: tmp_path)


def test_success_returns_output() -> None:
    res = run_headless("print('built'); print('  (50 %)')", 30, PY)
    assert res["success"] is True and res["returncode"] == 0
    assert res["output"] == "built\n  (50 %)"  # preserve script output
    text = format_headless_result(res)
    assert text.startswith("Headless FreeCAD script finished") and "reload_document" in text


def test_exception_reports_exit_code_and_traceback() -> None:
    res = run_headless("print('step 1')\nraise ValueError('Null shape')", 30, PY)
    assert res["success"] is False and res["returncode"] == 1
    assert "step 1" in res["output"] and "ValueError: Null shape" in res["output"]
    assert format_headless_result(res).startswith("Headless FreeCAD script FAILED: script failed (exit code 1)")


def test_native_crash_is_reported_not_propagated() -> None:
    if sys.platform == "win32":
        pytest.skip("POSIX signal exit status")
    res = run_headless("import os, resource, signal; resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); print('before', flush=True); os.kill(os.getpid(), signal.SIGSEGV)", 30, PY)
    assert res["success"] is False and res["crashed"] is True
    assert "SIGSEGV" in res["error"] and "GUI is unaffected" in res["error"]
    assert res["output"] == "before"


def test_timeout_kills_the_process() -> None:
    res = run_headless("import time; time.sleep(30)", 1, PY)
    assert res["success"] is False and res["timed_out"] is True
    assert "did not finish within 1 s" in res["error"]


def test_timeout_stops_child_before_it_can_write(tmp_path: Path) -> None:
    marker = tmp_path / "late-child-write"
    ready = tmp_path / "child-ready"
    release = tmp_path / "release-child"
    child = (
        "import time; from pathlib import Path; "
        f"Path({str(ready)!r}).touch(); "
        f"release=Path({str(release)!r}); deadline=time.monotonic()+10\n"
        "while not release.exists() and time.monotonic()<deadline: time.sleep(.02)\n"
        f"if release.exists(): Path({str(marker)!r}).write_text('late write')\n"
    )
    parent = (
        "import subprocess, sys, time; from pathlib import Path\n"
        f"subprocess.Popen([sys.executable, '-c', {child!r}], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n"
        f"while not Path({str(ready)!r}).exists(): time.sleep(.02)\n"
        "print('child started', flush=True); time.sleep(30)"
    )
    result = run_headless(parent, 2, PY)
    assert result["timed_out"] and "child started" in result["output"]
    release.touch()
    # Give a surviving child time to observe the release; the unfixed runner
    # reliably writes the marker here after returning its timeout response.
    time.sleep(.5)
    assert not marker.exists()


@pytest.mark.parametrize("exit_code", [0, 1])
def test_freecad_signal_handler_report_requires_failed_exit(exit_code: int) -> None:
    # Replay the FreeCAD 1.1.1 handler's stderr/exit contract using Python.
    result = run_headless(
        "import sys\nprint('Program received signal SIGSEGV, Segmentation fault.', file=sys.stderr)\n"
        f"sys.exit({exit_code})", 5, PY,
    )
    assert result["success"] is (exit_code == 0)
    if exit_code:
        assert result["crashed"] is True
        assert "reported a crash with SIGSEGV" in result["error"]
    else:
        assert "crashed" not in result


@pytest.mark.parametrize(
    ("output_code", "expected"),
    [
        ("print('started', flush=True)", "started"),
        ("print('warning', file=sys.stderr, flush=True)", "warning"),
        ("print('started', flush=True); print('warning', file=sys.stderr, flush=True)", "started\nwarning"),
        ("sys.stdout.buffer.write(b'progress \\xe3\\x81'); sys.stdout.flush()", "progress \ufffd"),
    ],
)
def test_timeout_preserves_partial_output_and_removes_script(
    tmp_path: Path, output_code: str, expected: str,
) -> None:
    result = run_headless(f"import sys, time\n{output_code}\ntime.sleep(30)", 0.5, PY)
    assert result["success"] is False and result["timed_out"] is True
    assert result["output"] == expected
    assert "within 0.5 s" in result["error"]
    assert list(tmp_path.iterdir()) == []


@pytest.mark.parametrize("timeout", [0, -1, float("inf"), float("nan")])
def test_invalid_timeout_never_launches_code(tmp_path: Path, timeout: float) -> None:
    result = run_headless("raise AssertionError('must not run')", timeout, PY)
    assert result["success"] is False
    assert "positive finite" in result["error"]
    assert list(tmp_path.iterdir()) == []


def test_start_failure_is_reported_and_removes_script(tmp_path: Path) -> None:
    result = run_headless("pass", 5, [str(tmp_path / "missing-freecadcmd")])
    assert result["success"] is False
    assert "could not start" in result["error"]
    assert list(tmp_path.iterdir()) == []


def test_snap_command_is_detected(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(headless.shutil, "which", lambda name: "/snap/bin/freecad.cmd" if name == "freecad.cmd" else None)
    assert headless.detect_freecadcmd() == ["/snap/bin/freecad.cmd"]


def test_missing_command_is_a_clear_error(monkeypatch) -> None:
    import freecad_mcp.headless as h

    monkeypatch.setattr(h, "detect_freecadcmd", lambda: None)
    res = run_headless("print(1)", 5, None)
    assert res["success"] is False and "freecadcmd not found" in res["error"]


def test_parse_command() -> None:
    assert parse_command(None) is None
    assert parse_command("flatpak run --command=freecadcmd org.freecad.FreeCAD") == [
        "flatpak", "run", "--command=freecadcmd", "org.freecad.FreeCAD",
    ]


@pytest.mark.parametrize(
    ("code", "timeout"),
    [
        ("print('before')\nraise ValueError('x')", 30),
        ("print('before')\nimport sys; sys.exit(0)", 30),
        ("print('before')\nimport time; time.sleep(30)", 1),
    ],
)
def test_unflushed_output_survives_abnormal_exit(code: str, timeout: float) -> None:
    # A pipe makes Python block-buffer stdout, as freecadcmd does; nothing in
    # these scripts flushes it.
    assert "before" in run_headless(code, timeout, PY)["output"].splitlines()


def test_unbuffering_prefix_leaves_no_names_in_the_script_namespace() -> None:
    res = run_headless("print(sorted(k for k in globals() if not k.startswith('__')))", 30, PY)
    assert res["output"] == "[]"


def test_parse_unquoted_executable_path(tmp_path: Path) -> None:
    executable = tmp_path / "Program Files" / "FreeCAD 1.1" / "freecadcmd.exe"
    executable.parent.mkdir(parents=True)
    executable.touch()
    assert parse_command(str(executable)) == [str(executable)]
    assert parse_command(executable.as_posix()) == [executable.as_posix()]


def test_parse_quoted_executable_with_arguments(tmp_path: Path) -> None:
    executable = tmp_path / "FreeCAD 1.1" / "freecadcmd.exe"
    executable.parent.mkdir()
    executable.touch()
    assert parse_command(f'"{executable}" --some-flag') == [
        str(executable), "--some-flag",
    ]


def test_parse_command_when_filename_probe_fails(monkeypatch: pytest.MonkeyPatch) -> None:
    def invalid_filename(_path: Path) -> bool:
        raise OSError("not a valid filename")

    monkeypatch.setattr(headless.Path, "is_file", invalid_filename)
    assert parse_command("flatpak run --command=freecadcmd org.freecad.FreeCAD") == [
        "flatpak", "run", "--command=freecadcmd", "org.freecad.FreeCAD",
    ]


def test_headless_cannot_read_the_open_mcp_stdin() -> None:
    # Keep the parent's stdin open, as a stdio MCP client does. The headless
    # child must see EOF, rather than waiting for or consuming protocol bytes.
    launcher = (
        "import json, sys; from freecad_mcp.headless import run_headless; "
        "print(json.dumps(run_headless("
        "\"import sys; print(repr(sys.stdin.read()))\", 2, [sys.executable])))"
    )
    with subprocess.Popen(
        [sys.executable, "-c", launcher], stdin=subprocess.PIPE,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
    ) as parent:
        try:
            parent.wait(timeout=10)  # communicate() would close stdin too soon
        except subprocess.TimeoutExpired:
            parent.kill()
            raise
        assert parent.stdout is not None and parent.stderr is not None
        assert parent.returncode == 0, parent.stderr.read()
        result = json.loads(parent.stdout.read())
    assert result["success"] is True, result
    assert result["output"] == "''"
