from hermes_cli.gateway import _runtime_health_lines
from hermes_constants import get_hermes_home


def test_runtime_health_lines_include_fatal_platform_and_startup_reason(monkeypatch):
    monkeypatch.setattr(
        "gateway.status.read_runtime_status",
        lambda: {
            "gateway_state": "startup_failed",
            "exit_reason": "telegram conflict",
            "platforms": {
                "telegram": {
                    "state": "fatal",
                    "error_message": "another poller is active",
                }
            },
        },
    )

    lines = _runtime_health_lines()

    assert "⚠ telegram: another poller is active" in lines
    assert "⚠ Last startup issue: telegram conflict" in lines


def test_runtime_status_running_pid_validates_live_gateway_record(monkeypatch):
    from gateway import status as status_mod

    runtime = {
        "pid": 12345,
        "kind": "hermes-gateway",
        "argv": ["/opt/hermes/hermes_cli/main.py", "gateway", "run", "--replace"],
        "start_time": 17,
        "boot_id": status_mod._get_boot_identity(),
        "home": str(get_hermes_home().resolve()),
        "gateway_state": "running",
    }
    monkeypatch.setattr(status_mod, "_pid_exists", lambda pid: pid == 12345)
    monkeypatch.setattr(status_mod, "_get_process_start_time", lambda pid: 17)
    monkeypatch.setattr(
        status_mod,
        "_read_process_cmdline",
        lambda pid: "python -m hermes_cli.main gateway run",
    )
    monkeypatch.setattr(
        status_mod, "_read_process_home", lambda pid: get_hermes_home()
    )

    assert status_mod.get_runtime_status_running_pid(runtime) == 12345


def test_runtime_status_running_pid_rejects_disconnected_telegram(monkeypatch):
    from gateway import status as status_mod

    runtime = {
        "pid": 12345,
        "gateway_state": "running",
        "platforms": {"telegram": {"state": "retrying"}},
    }
    monkeypatch.setattr(
        status_mod,
        "_record_matches_live_gateway",
        lambda *args: status_mod.ProcessIdentity.MATCH,
    )

    assert status_mod.get_runtime_status_running_pid(runtime) is None


def test_runtime_status_running_pid_rejects_stopped_record(monkeypatch):
    from gateway import status as status_mod

    runtime = {
        "pid": 12345,
        "kind": "hermes-gateway",
        "argv": ["/opt/hermes/hermes_cli/main.py", "gateway", "run", "--replace"],
        "gateway_state": "stopped",
    }
    monkeypatch.setattr(status_mod, "_pid_exists", lambda pid: True)

    assert status_mod.get_runtime_status_running_pid(runtime) is None
