"""Verify that /measure/select reads STATION_CODE and filters recipes via the server."""
import importlib
from unittest.mock import patch, MagicMock


def _reload_measure(monkeypatch, station_code=None):
    """Reload config and measure module under the given STATION_CODE env."""
    if station_code is None:
        monkeypatch.delenv("STATION_CODE", raising=False)
    else:
        monkeypatch.setenv("STATION_CODE", station_code)
    import config
    importlib.reload(config)
    import blueprints.measure
    importlib.reload(blueprints.measure)


def test_select_recipe_calls_station_endpoint(logged_in_client, monkeypatch):
    _reload_measure(monkeypatch, station_code="ST-TEST")
    from blueprints import measure as measure_bp_mod
    with patch.object(measure_bp_mod, "api_client") as mock_api:
        mock_api.get_station_recipes.return_value = [
            {"id": 1, "code": "R1", "name": "Recipe 1", "active": True},
        ]
        resp = logged_in_client.get("/measure/select")
        assert resp.status_code == 200
        mock_api.get_station_recipes.assert_called_once()
        args, kwargs = mock_api.get_station_recipes.call_args
        assert args[0] == "ST-TEST" or kwargs.get("station_code") == "ST-TEST"


def test_select_recipe_without_station_code_shows_error(logged_in_client, monkeypatch):
    _reload_measure(monkeypatch, station_code=None)
    resp = logged_in_client.get("/measure/select")
    assert resp.status_code == 503
    body = resp.data.lower()
    assert b"station_code" in body or b"stazione" in body
