"""Tests for /health endpoint ws_mode and expected_ws_connections fields (MISS-01).

Verifies that the /health response includes WS mode information for
monit/heartbeat observability (SC-4).
"""

from __future__ import annotations

import json
import socket
import urllib.error
import urllib.request

from opendeviationbar.sidecar.http_server import _health_state, _start_health_server


def _free_port() -> int:
    with socket.socket() as s:
        s.bind(("", 0))
        return s.getsockname()[1]


def _get_health_json(port: int) -> dict:
    """GET /health and return JSON body, handling non-200 status codes."""
    url = f"http://127.0.0.1:{port}/health"
    try:
        with urllib.request.urlopen(url, timeout=5) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        # 503 (unhealthy) still has a valid JSON body
        return json.loads(e.read())


class TestHealthWsMode:
    """MISS-01: /health includes ws_mode and expected_ws_connections."""

    def test_combined_mode(self):
        """ws_mode=combined shows 2 expected connections."""
        _health_state["ws_mode"] = "combined"
        _health_state["ws_symbols_count"] = 18
        port = _free_port()
        srv = _start_health_server(port=port, sse_enabled=False)
        assert srv is not None

        try:
            data = _get_health_json(port)
            assert data["ws_mode"] == "combined"
            assert data["expected_ws_connections"] == 2
        finally:
            srv.server_close()
            _health_state.pop("ws_mode", None)
            _health_state.pop("ws_symbols_count", None)

    def test_per_symbol_mode(self):
        """ws_mode=per_symbol shows symbol count as expected connections."""
        _health_state["ws_mode"] = "per_symbol"
        _health_state["ws_symbols_count"] = 18
        port = _free_port()
        srv = _start_health_server(port=port, sse_enabled=False)
        assert srv is not None

        try:
            data = _get_health_json(port)
            assert data["ws_mode"] == "per_symbol"
            assert data["expected_ws_connections"] == 18
        finally:
            srv.server_close()
            _health_state.pop("ws_mode", None)
            _health_state.pop("ws_symbols_count", None)

    def test_default_no_ws_mode(self):
        """When ws_mode is not set, defaults to 'unknown'."""
        _health_state.pop("ws_mode", None)
        _health_state.pop("ws_symbols_count", None)
        port = _free_port()
        srv = _start_health_server(port=port, sse_enabled=False)
        assert srv is not None

        try:
            data = _get_health_json(port)
            assert data["ws_mode"] == "unknown"
            assert data["expected_ws_connections"] == 0
        finally:
            srv.server_close()
