"""Regression tests for the in-container WebSocket client host resolution.

Issue #58993: when the dashboard binds to a wildcard (``0.0.0.0`` / ``::``),
the in-container WS clients built by ``_build_gateway_ws_url`` and
``_build_sidecar_url`` used the bind host verbatim, so the child TUI
dialed ``ws://0.0.0.0:9119/api/ws``. Behind a forward proxy whose
``NO_PROXY`` does not list ``0.0.0.0`` that wildcard dial is routed through
the proxy and fails the handshake.

The contract these tests pin down:

  * Wildcard bind (``0.0.0.0`` / ``::``) → client dials ``127.0.0.1``.
  * Loopback bind (``127.0.0.1``) → client dials ``127.0.0.1`` (unchanged).
  * LAN / non-wildcard bind (``192.168.1.5``) → client dials that exact
    address (no rewrite to loopback — the bind was deliberate).
  * Explicit ``HERMES_DASHBOARD_WS_HOST`` env var → wins always, regardless
    of the bind host.
  * ``app.state.bound_host`` is left untouched — the bind address used by
    the listener doesn't change.
"""

from __future__ import annotations


import pytest

from hermes_cli import web_server
import hermes_cli.web_server_chat as _web_server_chat


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture
def saved_app_state():
    """Snapshot and restore the bits of ``app.state`` the tests mutate.

    The dashboard's WS URL builders read three things off ``app.state``:
    ``bound_host``, ``bound_port``, ``auth_required``. We capture them so
    the suite doesn't leak state into other tests, then yield control.
    """
    saved = {
        "bound_host": getattr(web_server.app.state, "bound_host", None),
        "bound_port": getattr(web_server.app.state, "bound_port", None),
        "auth_required": getattr(web_server.app.state, "auth_required", None),
    }
    yield saved
    for key, value in saved.items():
        setattr(web_server.app.state, key, value)


@pytest.fixture
def clear_ws_host_env(monkeypatch):
    """Ensure no ``HERMES_DASHBOARD_WS_HOST`` leaks in from the test shell."""
    monkeypatch.delenv("HERMES_DASHBOARD_WS_HOST", raising=False)
    yield monkeypatch


def _set_bound(saved_app_state, host: str, port: int = 9119):
    web_server.app.state.bound_host = host
    web_server.app.state.bound_port = port
    web_server.app.state.auth_required = False


# ---------------------------------------------------------------------------
# _resolve_client_ws_host — direct unit tests
# ---------------------------------------------------------------------------


class TestResolveClientWsHost:
    def test_wildcard_ipv4_uses_loopback(self, saved_app_state, clear_ws_host_env):
        _set_bound(saved_app_state, "0.0.0.0")
        assert _web_server_chat._resolve_client_ws_host() == "127.0.0.1"

    def test_wildcard_ipv6_uses_loopback(self, saved_app_state, clear_ws_host_env):
        _set_bound(saved_app_state, "::")
        assert _web_server_chat._resolve_client_ws_host() == "127.0.0.1"

    def test_loopback_bind_unchanged(self, saved_app_state, clear_ws_host_env):
        _set_bound(saved_app_state, "127.0.0.1")
        assert _web_server_chat._resolve_client_ws_host() == "127.0.0.1"


    def test_public_dns_bind_preserved(self, saved_app_state, clear_ws_host_env):
        _set_bound(saved_app_state, "fly-app.example.dev")
        assert _web_server_chat._resolve_client_ws_host() == "fly-app.example.dev"


    def test_blank_env_falls_back_to_bind(
        self, saved_app_state, monkeypatch
    ):
        """An explicitly empty override (e.g. ``HERMES_DASHBOARD_WS_HOST=``)
        must NOT silently pin to loopback — it's an unset-by-accident, not
        an intent. Treat whitespace-only as absent and fall through."""
        monkeypatch.setenv("HERMES_DASHBOARD_WS_HOST", "   ")
        _set_bound(saved_app_state, "0.0.0.0")
        assert _web_server_chat._resolve_client_ws_host() == "127.0.0.1"


# ---------------------------------------------------------------------------
# _build_gateway_ws_url — end-to-end URL contract
# ---------------------------------------------------------------------------


class TestGatewayWsUrlHost:

    def test_ipv6_wildcard_bind_dials_loopback(
        self, saved_app_state, clear_ws_host_env
    ):
        _set_bound(saved_app_state, "::", port=9119)
        url = _web_server_chat._build_gateway_ws_url()
        assert url is not None
        assert url.startswith("ws://127.0.0.1:9119/api/ws")
        # The ``::`` must not leak into the client URL.
        assert "::" not in url


# ---------------------------------------------------------------------------
# _build_sidecar_url — end-to-end URL contract
# ---------------------------------------------------------------------------


class TestSidecarUrlHost:


    def test_no_bound_host_returns_none(
        self, saved_app_state, clear_ws_host_env
    ):
        web_server.app.state.bound_host = None
        web_server.app.state.bound_port = None
        assert _web_server_chat._build_sidecar_url("ch-1") is None
