Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
29.5 KB
Raw Blame
"""Sentinel Hub layers, mosaicking windows and date discovery (engine/sentinel.py)."""

from __future__ import annotations

import base64
import json
import io

import httpx
import pytest
from PIL import Image

from azimut.engine import sentinel


def _response(url, payload=None, text=None, status=200):
    return httpx.Response(
        status,
        content=(text if text is not None else json.dumps(payload)).encode(),
        request=httpx.Request("GET", url),
    )


# -- the WMTS template ---------------------------------------------------------


def test_wmts_url_omits_time_by_default():
    url = sentinel.wmts_url()
    assert "LAYER=TRUE_COLOR" in url
    # No TIME is the undated fallback, not "most recent": Sentinel Hub applies
    # the mosaicking order per pixel over the whole archive, so a swath edge in
    # the newest scene comes back filled from an older one. Callers send a day.
    assert "TIME=" not in url
    assert "{key}" in url and "{z}" in url and "{x}" in url and "{y}" in url


def test_wmts_url_dates_one_acquisition_when_both_ends_are_the_same_day():
    # the shape every caller asks for: one pass, which can be pointed at and
    # dated, with holes where that pass has no pixels
    url = sentinel.wmts_url("TRUE_COLOR", "2026-05-11", "2026-05-11")
    assert "TIME=2026-05-11/2026-05-11" in url


def test_wmts_url_carries_the_layer_and_the_window():
    url = sentinel.wmts_url("SWIR", "2026-05-01", "2026-05-31")
    assert "LAYER=SWIR" in url
    assert "TIME=2026-05-01/2026-05-31" in url


def test_wmts_url_ignores_a_half_open_window():
    # a window needs both ends; one date alone would silently mean something
    # other than what the caller thinks
    assert "TIME=" not in sentinel.wmts_url("SWIR", "2026-05-01", None)


def test_wmts_url_always_states_the_cloud_ceiling():
    # left unsaid, the instance's own filter applies (20% in the standard
    # template) and cloudy passes come back empty rather than cloudy
    assert "MAXCC=100" in sentinel.wmts_url()
    assert "MAXCC=20" in sentinel.wmts_url("TRUE_COLOR", None, None, 20)


# -- variant ids ---------------------------------------------------------------


def test_variant_id_of_the_plain_basemap_is_just_the_base_id():
    # the default layer with no window must not get a second name: it would
    # cache twice and read as two providers in provenance
    assert sentinel.variant_id("sentinel2") == "sentinel2"
    assert sentinel.variant_id("sentinel2", "TRUE_COLOR") == "sentinel2"


def test_variant_id_round_trips_through_parse_variant():
    packed = sentinel.variant_id("sentinel2", "SWIR", "2026-05-01", "2026-05-31")
    assert packed == "sentinel2~SWIR~2026-05-01~2026-05-31"
    base, _, spec = packed.partition("~")
    assert base == "sentinel2"
    assert sentinel.parse_variant(spec) == ("SWIR", "2026-05-01", "2026-05-31", 100)


def test_variant_id_keeps_a_windowed_default_layer():
    packed = sentinel.variant_id("sentinel2", "TRUE_COLOR", "2026-05-01", "2026-05-01")
    assert packed == "sentinel2~TRUE_COLOR~2026-05-01~2026-05-01"


def test_parse_variant_takes_a_bare_layer():
    assert sentinel.parse_variant("FALSE_COLOR") == ("FALSE_COLOR", None, None, 100)


def test_parse_variant_accepts_a_layer_the_catalogue_never_heard_of():
    # an instance serves whatever its configuration says; the catalogue is a
    # default, not a gate (a wrong one comes back as Sentinel Hub's own 400)
    assert sentinel.parse_variant("MY_CUSTOM_SCRIPT") == ("MY_CUSTOM_SCRIPT", None, None, 100)


@pytest.mark.parametrize(
    "spec",
    [
        "../../etc/passwd",  # the id is a URL path segment *and* a cache directory
        "TRUE COLOR",
        "true_color",  # layer names are upper-case; lower would 400 upstream
        "SWIR~2026-05-01",  # half a window
        "SWIR~2026-05-01~2026-05-31~extra",
        "SWIR~2026-13-01~2026-05-31",  # impossible month
        "SWIR~05/01/2026~2026-05-31",  # not ISO
        "SWIR~2026-05-31~2026-05-01",  # ends before it starts
        "",
    ],
)
def test_parse_variant_refuses_anything_ill_shaped(spec):
    with pytest.raises(ValueError):
        sentinel.parse_variant(spec)


def test_variant_id_carries_a_cloud_ceiling():
    packed = sentinel.variant_id("sentinel2", "SWIR", "2026-05-01", "2026-05-31", 20)
    assert packed == "sentinel2~SWIR~2026-05-01~2026-05-31~CC20"
    assert sentinel.parse_variant(packed.partition("~")[2]) == (
        "SWIR", "2026-05-01", "2026-05-31", 20
    )


def test_variant_id_carries_a_ceiling_without_a_window():
    packed = sentinel.variant_id("sentinel2", "TRUE_COLOR", None, None, 0)
    assert packed == "sentinel2~TRUE_COLOR~CC0"
    assert sentinel.parse_variant(packed.partition("~")[2]) == ("TRUE_COLOR", None, None, 0)


def test_variant_id_leaves_the_default_ceiling_off_the_id():
    # 100 is "no filter", which is the plain basemap: naming it would cache the
    # same tiles twice under two ids
    assert sentinel.variant_id("sentinel2", "TRUE_COLOR", None, None, 100) == "sentinel2"


@pytest.mark.parametrize("spec", ["SWIR~CC101", "SWIR~CC-5", "SWIR~CC", "SWIR~CC20~CC20"])
def test_parse_variant_refuses_an_impossible_ceiling(spec):
    with pytest.raises(ValueError):
        sentinel.parse_variant(spec)


def test_variant_label_reads_like_a_human_wrote_it():
    # no window sends no TIME, which blends the archive per pixel rather than
    # rendering the newest pass — the label must not promise a date
    assert sentinel.variant_label("SWIR", None, None).endswith("undated mosaic")
    assert "2026-05-01 → 2026-05-31" in sentinel.variant_label("SWIR", "2026-05-01", "2026-05-31")
    # a single-day window is a day, not a range from a day to itself
    assert sentinel.variant_label("SWIR", "2026-05-01", "2026-05-01").endswith("2026-05-01")
    # a ceiling changes the pixels, so it is part of what the capture was from
    assert sentinel.variant_label("SWIR", None, None, 20).endswith("≤20% cloud")
    assert "cloud" not in sentinel.variant_label("SWIR", None, None, 100)


# -- date discovery ------------------------------------------------------------


def test_dates_collapses_granules_per_day_newest_first():
    captured = {}

    def get(url, params=None, **kwargs):
        captured["url"] = url
        captured["params"] = params
        return _response(
            url,
            {
                "features": [
                    {"properties": {"date": "2026-05-01", "cloudCoverPercentage": 80.0}},
                    # same day, second granule covering the point — the clearer
                    # one is the one worth reporting
                    {"properties": {"date": "2026-05-01", "cloudCoverPercentage": 12.5}},
                    {"properties": {"date": "2026-05-11", "cloudCoverPercentage": 3.0}},
                    {"properties": {"date": "not-a-date"}},  # never trust the wire
                ]
            },
        )

    found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)
    assert found == [
        {"date": "2026-05-11", "cloud": 3.0, "granules": 1},
        {"date": "2026-05-01", "cloud": 12.5, "granules": 2},
    ]
    assert "/ogc/wfs/inst-uuid" in captured["url"]
    assert captured["params"]["TYPENAMES"] == "DSS2"  # L2A — what the basemap renders
    assert captured["params"]["TIME"] == "2026-05-01/2026-05-31"


def _square(lat, lon, half=0.5):
    """A granule footprint around a point, GeoJSON order (lon, lat)."""
    return {
        "type": "Polygon",
        "coordinates": [[
            [lon - half, lat - half], [lon + half, lat - half],
            [lon + half, lat + half], [lon - half, lat + half],
            [lon - half, lat - half],
        ]],
    }


def test_dates_drops_a_granule_whose_imagery_misses_the_point():
    """A granule's *box* can reach the point while its swath doesn't — that day
    renders black. WFS answers on the box, so the footprint has to be checked or
    the date list promises imagery that isn't there."""

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [
            # covers the point
            {"properties": {"date": "2026-05-11", "cloudCoverPercentage": 2},
             "geometry": _square(48.85, 2.29)},
            # box intersects the search area, footprint is a province away
            {"properties": {"date": "2026-05-04", "cloudCoverPercentage": 1},
             "geometry": _square(45.0, 6.0)},
        ]})

    found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)
    assert [entry["date"] for entry in found] == ["2026-05-11"]


def test_dates_keeps_a_granule_whatever_axis_order_the_service_used():
    """GeoJSON says lon/lat; an OGC service asked for EPSG:4326 may answer
    lat/lon. Read backwards, every footprint on Earth would be rejected."""
    swapped = {
        "type": "Polygon",
        "coordinates": [[[48.35, 1.79], [49.35, 1.79], [49.35, 2.79], [48.35, 2.79], [48.35, 1.79]]],
    }

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [
            {"properties": {"date": "2026-05-11"}, "geometry": swapped}
        ]})

    found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)
    assert [entry["date"] for entry in found] == ["2026-05-11"]


def test_dates_keeps_a_pass_whose_geometry_it_cannot_read():
    """Never drop a real pass over a guess: no geometry means no evidence."""

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [
            {"properties": {"date": "2026-05-11"}},
            {"properties": {"date": "2026-05-08"}, "geometry": {"type": "Point", "coordinates": [2, 48]}},
        ]})

    found = sentinel.dates("inst-uuid", 48.8584, 2.2945, "2026-05-01", "2026-05-31", get=get)
    assert [entry["date"] for entry in found] == ["2026-05-11", "2026-05-08"]


def test_dates_sends_a_latitude_first_bbox():
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _response(url, {"features": []})

    sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)
    # EPSG:4326 declares latitude first; lon/lat order would put the box in the
    # Indian Ocean and quietly report "no imagery"
    assert captured["SRSNAME"] == "EPSG:4326"
    lat_min, lon_min, lat_max, lon_max = (float(v) for v in captured["BBOX"].split(","))
    assert lat_min < 48.0 < lat_max
    assert lon_min < 2.0 < lon_max


def test_dates_asks_for_every_pass_however_cloudy():
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _response(url, {"features": []})

    sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)
    # the calendar colours days by cloud and the user's own ceiling greys them
    # out; a list already cut upstream would hide passes we never said we hid
    assert captured["MAXCC"] == "100"


def test_dates_reports_a_day_the_service_gave_no_cloud_figure_for():
    def get(url, params=None, **kwargs):
        return _response(url, {"features": [{"properties": {"date": "2026-05-01"}}]})

    found = sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)
    assert found == [{"date": "2026-05-01", "cloud": None, "granules": 1}]


def test_dates_raises_rather_than_report_an_empty_sky():
    def get(url, params=None, **kwargs):
        return _response(url, {}, status=500)

    # "the lookup failed" and "there are no passes here" are different facts and
    # must never render as the same empty list
    with pytest.raises(httpx.HTTPStatusError):
        sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get)


# -- acquisitions over a drawn area -------------------------------------------


def _rect(west, south, east, north):
    """A drawn area's ring, the way `analysis_models.Zone.ring()` gives it."""
    return [(west, south), (east, south), (east, north), (west, north)]


def _granule(day, west, south, east, north, cloud=5.0):
    return {
        "properties": {"date": day, "cloudCoverPercentage": cloud},
        "geometry": {"type": "Polygon", "coordinates": [[
            [west, south], [east, south], [east, north], [west, north], [west, south],
        ]]},
    }


def test_acquisitions_measures_how_much_of_the_area_a_pass_reaches():
    """The number a crosshair lookup cannot give. Sentinel-2 flies 290 km swaths,
    so a wide area can have no single day covering it — and pinned to one date
    anyway, the rest of the sweep reads nodata."""
    area = _rect(2.0, 48.0, 4.0, 49.0)

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [
            # covers the lot
            _granule("2026-05-11", 1.5, 47.5, 4.5, 49.5, cloud=3.0),
            # only the western half
            _granule("2026-05-08", 1.5, 47.5, 3.0, 49.5, cloud=9.0),
        ]})

    found = sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)
    whole, half = found["dates"]
    assert whole["date"] == "2026-05-11"  # newest first
    assert whole["coverage"] == 1.0
    assert half["date"] == "2026-05-08"
    assert 0.45 < half["coverage"] < 0.55
    assert not found["truncated"]


def test_acquisitions_adds_up_two_granules_of_the_same_day():
    """One day, two granules of the same orbit: together they cover the area,
    and reporting either alone would call a usable date partial."""
    area = _rect(2.0, 48.0, 4.0, 49.0)

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [
            _granule("2026-05-11", 1.5, 47.5, 3.0, 49.5, cloud=40.0),
            _granule("2026-05-11", 3.0, 47.5, 4.5, 49.5, cloud=4.0),
        ]})

    entry = sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["dates"][0]
    assert entry["coverage"] == 1.0
    assert entry["granules"] == 2
    # the clearer of the two is the one worth reporting
    assert entry["cloud"] == 4.0


def test_acquisitions_drops_a_day_that_reaches_none_of_the_area():
    area = _rect(2.0, 48.0, 2.5, 48.5)

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [_granule("2026-05-04", 8.0, 44.0, 9.0, 45.0)]})

    # a box may intersect the search area while its swath is a province away
    assert sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["dates"] == []


def test_acquisitions_weighs_a_small_area_beside_a_large_one():
    """Every drawn area gets sampled, so a pass that misses the small one cannot
    report as full cover just because the big one dwarfs it."""
    big = _rect(2.0, 48.0, 4.0, 49.0)
    small = _rect(10.0, 40.0, 10.02, 40.02)

    def get(url, params=None, **kwargs):
        return _response(url, {"features": [_granule("2026-05-11", 1.5, 47.5, 4.5, 49.5)]})

    entry = sentinel.acquisitions("inst-uuid", [big, small], "2026-05-01", "2026-05-31", get=get)["dates"][0]
    assert entry["coverage"] < 1.0


def test_acquisitions_asks_about_the_whole_set_latitude_first():
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _response(url, {"features": []})

    sentinel.acquisitions(
        "inst-uuid", [_rect(2.0, 48.0, 2.5, 48.5), _rect(6.0, 44.0, 6.5, 44.5)],
        "2026-05-01", "2026-05-31", get=get,
    )
    lat_min, lon_min, lat_max, lon_max = (float(v) for v in captured["BBOX"].split(","))
    # one box around both areas, and EPSG:4326's declared latitude-first order
    assert lat_min < 44.0 and lat_max > 48.5
    assert lon_min < 2.0 and lon_max > 6.5


def test_acquisitions_says_when_the_catalogue_stopped_short():
    """Silently truncated, the list reads as "these are all the passes" while
    the older half is missing."""
    area = _rect(2.0, 48.0, 2.5, 48.5)
    crowd = [_granule(f"2026-05-{day:02d}", 1.5, 47.5, 3.0, 49.5) for day in range(1, 31)]

    def get(url, params=None, **kwargs):
        return _response(url, {"features": crowd * 4})  # 120, past the 100 ceiling

    assert sentinel.acquisitions("inst-uuid", [area], "2026-05-01", "2026-05-31", get=get)["truncated"]


def _paged(pages):
    """A catalogue that answers ``pages`` in turn, by FEATURE_OFFSET."""
    asked = []

    def get(url, params=None, **kwargs):
        offset = int(params.get("FEATURE_OFFSET", 0))
        asked.append(offset)
        return _response(url, {"features": pages[offset // sentinel._MAX_FEATURES]})

    return get, asked


def test_a_full_page_is_followed_by_the_next_until_one_is_short():
    """Granules come newest first, so the first 100 of a long window are its
    newest weeks: stopping there lost the oldest passes, silently for a point."""
    area = _rect(2.0, 48.0, 2.5, 48.5)
    newer = [_granule(f"2026-05-{day:02d}", 1.5, 47.5, 3.0, 49.5) for day in range(31, 1, -1)] * 4
    older = [_granule("2026-04-30", 1.5, 47.5, 3.0, 49.5)]
    get, asked = _paged([newer[:100], older])
    metered = []

    found = sentinel.acquisitions("inst-uuid", [area], "2026-04-01", "2026-05-31", get=get,
                                  on_request=lambda: metered.append(1))
    assert asked == [0, 100]
    assert len(metered) == 2  # each page a request on the meter
    assert not found["truncated"]
    assert found["dates"][-1]["date"] == "2026-04-30"


def test_a_lookup_stops_after_its_last_page_and_says_it_was_cut():
    crowd = [_granule("2026-05-01", 1.5, 47.5, 3.0, 49.5)] * sentinel._MAX_FEATURES
    get, asked = _paged([crowd] * (sentinel._MAX_PAGES + 2))
    found = sentinel.acquisitions("inst-uuid", [_rect(2.0, 48.0, 2.5, 48.5)], "2026-05-01", "2026-05-31", get=get)
    assert len(asked) == sentinel._MAX_PAGES
    assert found["truncated"]


def test_a_point_lookup_pages_too():
    first = [{"properties": {"date": f"2026-05-{1 + i % 28:02d}", "cloudCoverPercentage": 5.0}}
             for i in range(sentinel._MAX_FEATURES)]
    last = [{"properties": {"date": "2026-04-02", "cloudCoverPercentage": 5.0}}]
    get, asked = _paged([first, last])
    found = sentinel.dates("inst-uuid", 48.0, 2.0, "2026-04-01", "2026-05-31", get=get)
    assert asked == [0, 100]
    assert found[-1]["date"] == "2026-04-02"


def test_a_failed_page_is_still_counted():
    def get(url, params=None, **kwargs):
        return _response(url, text="busy", status=503)

    metered = []
    with pytest.raises(httpx.HTTPStatusError):
        sentinel.dates("inst-uuid", 48.0, 2.0, "2026-05-01", "2026-05-31", get=get,
                       on_request=lambda: metered.append(1))
    assert metered == [1]


@pytest.mark.parametrize("start,end", [
    ("2026-13-01", "2026-05-31"), ("2026-05-01", "not-a-date"), ("2026-05-31", "2026-05-01"),
])
def test_acquisitions_refuses_a_malformed_window(start, end):
    with pytest.raises(ValueError):
        sentinel.acquisitions("inst-uuid", [_rect(2.0, 48.0, 2.5, 48.5)], start, end,
                              get=lambda *a, **k: _response("x", {"features": []}))


def test_acquisitions_refuses_an_empty_area_set():
    with pytest.raises(ValueError):
        sentinel.acquisitions("inst-uuid", [], "2026-05-01", "2026-05-31",
                              get=lambda *a, **k: _response("x", {"features": []}))


# -- rendered coverage --------------------------------------------------------


def _mask_response(url, values):
    image = Image.new("L", (8, 8))
    image.putdata(values)
    payload = io.BytesIO()
    image.save(payload, format="PNG")
    return httpx.Response(
        200, content=payload.getvalue(), request=httpx.Request("GET", url)
    )


def test_coverage_uses_the_selected_layer_and_day():
    captured = {}

    def get(url, params=None, **kwargs):
        captured["url"] = url
        captured["params"] = params
        return _mask_response(url, [0] * 63 + [255])

    result = sentinel.coverage(
        "inst-uuid", 48.8584, 2.2945, "SWIR", "2026-05-11", get=get
    )

    assert result == {
        "available": True,
        "coverage": 0.016,
        "date": "2026-05-11",
        "layer": "SWIR",
        "maxcc": 100,
    }
    assert captured["url"].endswith("/ogc/wms/inst-uuid")
    assert captured["params"]["LAYERS"] == "SWIR"
    assert captured["params"]["TIME"] == "2026-05-11/2026-05-11"
    assert captured["params"]["FORMAT"] == "image/png"
    assert captured["params"]["EVALSCRIPT"]


def test_coverage_probes_at_the_ceiling_the_map_will_render_with():
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _mask_response(url, [0] * 64)

    result = sentinel.coverage(
        "inst-uuid", 48.0, 2.0, "TRUE_COLOR", "2026-05-11", 20, get=get
    )
    # above the ceiling Sentinel Hub renders nothing, so a probe at 100% would
    # promise imagery the tiles are not going to show
    assert captured["MAXCC"] == "20"
    assert result["maxcc"] == 20


@pytest.mark.parametrize("maxcc", [101, -1])
def test_coverage_rejects_an_impossible_ceiling(maxcc):
    with pytest.raises(ValueError):
        sentinel.coverage("inst-uuid", 48.0, 2.0, "TRUE_COLOR", "2026-05-11", maxcc)


def test_coverage_reports_no_source_pixels():
    result = sentinel.coverage(
        "inst-uuid", 48.8584, 2.2945, "TRUE_COLOR", "2026-05-11",
        get=lambda url, **kwargs: _mask_response(url, [0] * 64),
    )
    assert result["available"] is False
    assert result["coverage"] == 0.0


@pytest.mark.parametrize(
    ("layer", "day"),
    [("../SWIR", "2026-05-11"), ("SWIR", "2026-02-30")],
)
def test_coverage_rejects_malformed_layer_or_day(layer, day):
    with pytest.raises(ValueError):
        sentinel.coverage("inst-uuid", 48.0, 2.0, layer, day)


def test_coverage_rejects_a_non_image_response():
    def get(url, **kwargs):
        return _response(url, text="<ExceptionReport />")

    with pytest.raises(sentinel.CoverageError, match="no readable image"):
        sentinel.coverage(
            "inst-uuid", 48.0, 2.0, "TRUE_COLOR", "2026-05-11", get=get
        )


# -- layer discovery -----------------------------------------------------------

_CAPABILITIES = """<?xml version="1.0"?>
<Capabilities xmlns="http://www.opengis.net/wmts/1.0"
              xmlns:ows="http://www.opengis.net/ows/1.1">
  <Contents>
    <Layer><ows:Identifier>TRUE_COLOR</ows:Identifier><ows:Title>True color</ows:Title></Layer>
    <Layer><ows:Identifier>MY_SHIPS</ows:Identifier><ows:Title>Vessel script</ows:Title></Layer>
    <Layer><ows:Identifier>bad id</ows:Identifier><ows:Title>unusable</ows:Title></Layer>
  </Contents>
</Capabilities>
"""


def test_capabilities_layers_asks_the_instance_and_keeps_our_hints():
    def get(url, params=None, **kwargs):
        assert params["REQUEST"] == "GetCapabilities"
        return _response(url, text=_CAPABILITIES)

    found = sentinel.capabilities_layers("inst-uuid", get=get)
    assert [entry["id"] for entry in found] == ["TRUE_COLOR", "MY_SHIPS"]
    # a layer we know keeps the reason to pick it; one we don't still gets offered
    assert found[0]["hint"]
    assert found[1] == {"id": "MY_SHIPS", "label": "Vessel script", "hint": ""}


def test_capabilities_layers_drops_names_that_could_not_be_asked_for():
    def get(url, params=None, **kwargs):
        return _response(url, text=_CAPABILITIES)

    # "bad id" can't survive a variant id (URL path segment + cache directory),
    # so offering it would only produce a broken selection
    assert all(" " not in entry["id"] for entry in sentinel.capabilities_layers("i", get=get))


# -- band frames ----------------------------------------------------------------


def _rgba_response(url, size):
    payload = io.BytesIO()
    Image.new("RGBA", size, (200, 4, 0, 255)).save(payload, format="PNG")
    return httpx.Response(200, content=payload.getvalue(), request=httpx.Request("GET", url))


BOX = (250_000.0, 6_250_000.0, 251_000.0, 6_250_600.0)


@pytest.mark.parametrize(
    ("index", "high", "low"),
    [("ndvi", "B08", "B04"), ("ndwi", "B03", "B08"), ("nbr", "B08", "B12"), ("ndbi", "B11", "B08")],
)
def test_band_frame_asks_for_the_named_normalised_difference(index, high, low):
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _rgba_response(url, (320, 192))

    body = sentinel.band_frame("inst-uuid", BOX, 320, 192, "2026-05-11", f"change-{index}", 30, get=get)

    script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")
    assert f'bands: ["{high}", "{low}"' in script
    assert f"(p.{high}) - (p.{low})" in script
    assert captured["CRS"] == "EPSG:3857"
    assert captured["BBOX"] == "250000.0,6250000.0,251000.0,6250600.0"
    assert (captured["WIDTH"], captured["HEIGHT"]) == ("320", "192")
    assert captured["TIME"] == "2026-05-11/2026-05-11"
    assert captured["MAXCC"] == "30"
    assert body.startswith(b"\x89PNG")


@pytest.mark.parametrize(
    "kwargs",
    [
        {"index": "change-evi"},
        {"bbox": (10.0, 10.0, 5.0, 20.0)},
        {"bbox": (0.0, 0.0, 30_000_000.0, 10.0)},
        {"width": 4096},
        {"day": "2026-13-40"},
    ],
)
def test_band_frame_refuses_a_malformed_request_before_sending_it(kwargs):
    asked = dict(bbox=BOX, width=64, height=64, day="2026-05-11", index="change-ndvi")
    asked.update(kwargs)

    def get(*args, **kw):  # pragma: no cover - must never run
        raise AssertionError("nothing may be sent")

    with pytest.raises(ValueError):
        sentinel.band_frame(
            "inst-uuid", asked["bbox"], asked["width"], asked["height"],
            asked["day"], asked["index"], get=get,
        )


def test_band_frame_refuses_an_image_of_the_wrong_size():
    with pytest.raises(sentinel.CoverageError):
        sentinel.band_frame(
            "inst-uuid", BOX, 64, 64, "2026-05-11", "change-ndvi",
            get=lambda url, **kw: _rgba_response(url, (32, 32)),
        )


def _detect_script(product):
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _rgba_response(url, (64, 64))

    sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", product, get=get)
    return base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")


def test_the_vessel_product_reads_both_infrareds_water_and_the_sky():
    script = _detect_script("vessel")
    assert 'bands: ["B03", "B08", "B11", "SCL", "dataMask"]' in script
    # Near-infrared first and never zero where there is data, so a dark sea
    # still reads as a reading; short-wave infrared, NDWI, then the sky byte.
    assert f"Math.max(1, Math.min(255, Math.round((p.B08) * {255 * sentinel.BAND_GAIN:g})))" in script
    assert f"Math.round((p.B11) * {255 * sentinel.BAND_GAIN:g})" in script
    assert "(p.B03 - p.B08) / (p.B03 + p.B08)" in script
    assert f"p.SCL + (p.B08 < {sentinel.DARK_REFLECTANCE} ? {sentinel.DARK_FLAG} : 0)" in script
    assert "if (!p.dataMask) return [0, 0, 0, 0];" in script


def test_the_fire_product_measures_against_b8a_on_b12s_own_grid():
    script = _detect_script("fire")
    assert 'bands: ["B8A", "B11", "B12", "SCL", "dataMask"]' in script
    assert "p.B12 / p.B11" in script
    assert "p.B12 / p.B8A" in script
    assert "p.B08" not in script   # 10 m against 20 m fakes ratios along sharp edges
    assert f"p.B8A < {sentinel.DARK_REFLECTANCE}" in script


def test_the_surface_product_gives_short_wave_infrared_room_over_desert():
    script = _detect_script("surface")
    assert 'bands: ["B04", "B08", "B11", "SCL", "dataMask"]' in script
    assert f"Math.round((p.B11) * {255 * sentinel.SWIR_GAIN:g})" in script


def test_detect_indices_are_sums_of_bands_so_bare_soil_fits():
    script = _detect_script("index-bsi")
    assert '"B11", "B04", "B08", "B02", "SCL", "dataMask"' in script
    assert "((p.B11 + p.B04) - (p.B08 + p.B02))" in script
    # the dark flag still needs B08, and a normalised difference that lacks it asks for it
    assert '"B03", "B11", "B08", "SCL", "dataMask"' in _detect_script("index-mndwi")


def test_difference_frames_carry_the_same_sky_byte_detect_measures():
    """The browser decodes R = index, G = sky, A = data; a canvas needs that alpha."""
    captured = {}

    def get(url, params=None, **kwargs):
        captured.update(params)
        return _rgba_response(url, (64, 64))

    sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "change-ndvi", get=get)
    script = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")
    assert f"p.SCL + (p.B08 < {sentinel.DARK_REFLECTANCE} ? {sentinel.DARK_FLAG} : 0), 0, 255]" in script
    # The cloud filter over the picture methods asks for the sky and nothing else.
    sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "change-sky", get=get)
    sky = base64.b64decode(captured["EVALSCRIPT"]).decode("ascii")
    assert 'bands: ["B08", "SCL", "dataMask"]' in sky
    assert "return [0, p.SCL" in sky


def test_band_frame_refuses_a_product_it_has_no_evalscript_for():
    def get(*args, **kwargs):  # pragma: no cover - must never run
        raise AssertionError("nothing may be sent")

    with pytest.raises(ValueError):
        sentinel.band_frame("inst-uuid", BOX, 64, 64, "2026-05-11", "thermal", get=get)
    assert sentinel.PRODUCTS == {
        "vessel", "fire", "surface", "change-sky", "sar", "sar-picture", "water",
        *(f"index-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),
        *(f"change-{name}" for name in ("ndvi", "ndwi", "mndwi", "nbr", "ndbi", "bsi")),
    }


def test_radar_label_names_a_pass_and_says_so_when_there_is_none():
    assert sentinel.radar_label("2026-05-14", "05:42:10") == "2026-05-14 05:42 UTC"
    assert sentinel.radar_label("2026-05-14", "") == "2026-05-14"
    # same defect as the optical label: without a day the tiles blend every pass
    # over the point, which mixes looks from opposite sides of the track
    assert sentinel.radar_label("", "") == "undated mosaic"


def test_radar_wmts_url_sends_no_time_only_when_it_has_no_pass():
    dated = sentinel.radar_wmts_url("S1_VV", "2026-05-14", "05:42:10")
    assert "TIME=" in dated
    assert "EVALSCRIPT=" in dated
    assert "TIME=" not in sentinel.radar_wmts_url("S1_VV")