"""
Module: test_sandbox_cmd
Description: Tests for sandbox lifecycle commands (status, stop) and internal helpers.

Implements:
    - docs/cli/reference.md#huitzo-sandbox
    - docs/cli/agent-integration.md#sandbox-lifecycle
"""

from __future__ import annotations

import os
from pathlib import Path

from huitzo_cli.commands.sandbox import _cleanup_pidfile, _is_process_alive
from huitzo_cli.sandbox.connection import write_sidecar


class TestIsProcessAlive:
    """Test the _is_process_alive() helper."""

    def test_current_pid_is_alive(self) -> None:
        assert _is_process_alive(os.getpid()) is True

    def test_pid_zero_is_not_alive(self) -> None:
        assert _is_process_alive(0) is False

    def test_negative_pid_is_not_alive(self) -> None:
        assert _is_process_alive(-1) is False


class TestCleanupPidfile:
    """Test _cleanup_pidfile() removes pidfile and sidecar."""

    def test_removes_pidfile_and_sidecar(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "sandbox.pid"
        pidfile.write_text("12345")
        write_sidecar(pidfile, "http://localhost:8080", "tok", 3)

        sidecar = pidfile.with_suffix(".json")
        assert pidfile.exists()
        assert sidecar.exists()

        _cleanup_pidfile(pidfile)

        assert not pidfile.exists()
        assert not sidecar.exists()

    def test_noop_when_pidfile_missing(self, temp_dir: Path) -> None:
        pidfile = temp_dir / "nonexistent.pid"
        # Should not raise
        _cleanup_pidfile(pidfile)


class TestSandboxStatusNoProcess:
    """Test sandbox status when no pidfile exists."""

    def test_status_no_pidfile(self, cli_runner: "CliRunner", temp_dir: Path) -> None:  # noqa: F821
        """status command reports no sandbox running when pidfile is absent."""
        from typer.testing import CliRunner as _CliRunner

        from huitzo_cli.commands.sandbox import sandbox_app

        runner = _CliRunner()
        pidfile = temp_dir / "nope.pid"
        result = runner.invoke(sandbox_app, ["status", "--pidfile", str(pidfile)])

        assert result.exit_code == 0
        assert "No sandbox running" in result.output


class TestSandboxStopNoProcess:
    """Test sandbox stop when no pidfile exists."""

    def test_stop_no_pidfile(self, temp_dir: Path) -> None:
        from typer.testing import CliRunner

        from huitzo_cli.commands.sandbox import sandbox_app

        runner = CliRunner()
        pidfile = temp_dir / "nope.pid"
        result = runner.invoke(sandbox_app, ["stop", "--pidfile", str(pidfile)])

        assert result.exit_code == 1
