"""Unit: the daemon-process-name resolution honours the
`MGF_TEST_SUPERVISOR_DAEMON_PROCESS_NAME` env var.

The supervisor was extracted from `mgf-hrb` (which has a
daemon — `mgf-hrb-server`) into the mgf-common test-bed (which
has no daemon). The extraction hard-coded `DAEMON_PROCESS_NAME
= None`. The env-var override lets daemon-bearing adopters like
mgf-hrb (and future workers) re-enable the probe without forking
the library.

Symmetric in shape with the `MGF_TEST_SUPERVISOR_REPO_ROOT`
pattern pinned by `tests/unit/test_repo_root_discovery.py`.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.test_supervisor import diagnostics

if TYPE_CHECKING:
    import pytest

_ENV_VAR = "MGF_TEST_SUPERVISOR_DAEMON_PROCESS_NAME"


class TestDaemonProcessNameResolution:
    """`_daemon_process_name()` resolves env-var → constant → None."""

    def test_unset_env_falls_back_to_module_constant(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """No env var, no constant override → None. This is the
        baseline mgf-common state — no daemon probed, daemon_state()
        returns empty string, failure bundles show "(empty)" for
        the PROCESS STATE section."""
        monkeypatch.delenv(_ENV_VAR, raising=False)
        monkeypatch.setattr(diagnostics, "DAEMON_PROCESS_NAME", None)
        assert diagnostics._daemon_process_name() is None

    def test_unset_env_with_constant_returns_constant(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """No env var, but module constant patched → use constant.
        This is the "edit the library locally" path; works but
        forks the source."""
        monkeypatch.delenv(_ENV_VAR, raising=False)
        monkeypatch.setattr(diagnostics, "DAEMON_PROCESS_NAME", "fallback-daemon")
        assert diagnostics._daemon_process_name() == "fallback-daemon"

    def test_env_var_overrides_module_constant(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """Env var present → wins over the module constant. This is
        the federation pattern: adopter projects (e.g. mgf-hrb) set
        the env var in `.envrc` / conftest / CI and the supervisor
        library stays unchanged."""
        monkeypatch.setenv(_ENV_VAR, "mgf-hrb-server")
        monkeypatch.setattr(diagnostics, "DAEMON_PROCESS_NAME", "fallback-daemon")
        assert diagnostics._daemon_process_name() == "mgf-hrb-server"

    def test_env_var_set_without_constant(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """Env var present, constant None → use env var. The
        common mgf-hrb adoption shape."""
        monkeypatch.setenv(_ENV_VAR, "mgf-hrb-server")
        monkeypatch.setattr(diagnostics, "DAEMON_PROCESS_NAME", None)
        assert diagnostics._daemon_process_name() == "mgf-hrb-server"

    def test_empty_env_var_treated_as_unset(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """A defensively-exported-but-empty env var (`export
        MGF_TEST_SUPERVISOR_DAEMON_PROCESS_NAME=`) must not enable
        the probe with a bogus name — fall back to the constant."""
        monkeypatch.setenv(_ENV_VAR, "")
        monkeypatch.setattr(diagnostics, "DAEMON_PROCESS_NAME", None)
        assert diagnostics._daemon_process_name() is None


class TestDaemonStateBehaviour:
    """`daemon_state()` uses the resolved name end-to-end."""

    def test_no_daemon_configured_returns_empty(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """No env, no constant → empty string (the silent-no-op
        path mgf-common relies on)."""
        monkeypatch.delenv(_ENV_VAR, raising=False)
        monkeypatch.setattr(diagnostics, "DAEMON_PROCESS_NAME", None)
        assert diagnostics.daemon_state() == ""

    def test_daemon_configured_but_not_running_reports_so(
        self,
        monkeypatch: pytest.MonkeyPatch,
    ) -> None:
        """Env var set to a name no process matches → human-readable
        "no `X` processes running". The bundle still records that we
        LOOKED (vs the silent-no-op case)."""
        # A name unlikely to match any real process on the test host.
        unlikely_name = "mgf-impossible-daemon-name-xyz"
        monkeypatch.setenv(_ENV_VAR, unlikely_name)
        out = diagnostics.daemon_state()
        # Either "no `…` processes running" (pgrep present + matched
        # nothing) or "(pgrep not available …)" (pgrep missing). Both
        # are acceptable; the wire is that the function REPORTS rather
        # than returns empty.
        assert out, "daemon_state() must report when a name is configured"
        assert (unlikely_name in out) or ("pgrep not available" in out), (
            f"unexpected daemon_state output: {out!r}"
        )
