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
74.5 KB
Raw Blame
"""Local analyzer behavior, bounds, provenance and persistence boundaries."""

import io
from copy import deepcopy

import numpy as np
import pytest
from PIL import Image

from azimut import __version__, config, layout
from azimut.api import analyzers as analyzers_api
from azimut.engine import analyzers, sentinel, tilecache, workqueue
from azimut.engine.analysis_models import (
    BUILTINS,
    METHODS,
    SIZES,
    Parameters,
    Recipe,
    RunInput,
    Source,
    Zone,
)
from azimut.workspace import Case
from analyzerfixture import (
    BARE,
    CLOUD,
    DARK,
    EDGE,
    PAD,
    SENTINEL_TILE,
    UNSURE,
    VEGETATION,
    WATER,
    analyzer_case,
    at,
    code,
    fire_frame,
    flame,
    glinted_sea,
    hull,
    index_byte,
    index_frame,
    run,
    sample_input,
    sea,
    seed,
    seed_images,
    sentinel_input,
    surface,
    zone,
)


@pytest.fixture
def scenario(client, monkeypatch):
    return analyzer_case(client, monkeypatch)


# -- runs, review and evidence ------------------------------------------------------


def test_a_day_is_read_whole_whatever_its_tile_s_cloud(client, scenario, monkeypatch):
    """Sentinel Hub drops a whole tile above MAXCC, so a day picked over the
    ceiling used to come back blank and the sweep read nothing. The ceiling
    only chooses the newest pass now; the sky byte keeps the clouds out."""
    from analyzerfixture import _png

    case, body = scenario
    body["offline"] = False
    assert body["b"]["maxcc"] < sentinel.DEFAULT_MAXCC
    client.put("/api/settings/keys", json={"sentinelhub": "INSTANCE"})
    monkeypatch.setattr(analyzers.tilecache, "get", lambda *args, **kwargs: None)
    read, pictures = [], []

    def band_frame(instance, box, width, height, day, product, maxcc, **kwargs):
        read.append(maxcc)
        return _png(surface())

    class Stream:
        status_code = 200

        def __init__(self, url):
            pictures.append(url)

        def __enter__(self):
            return self

        def __exit__(self, *exc):
            return False

        def raise_for_status(self):
            return None

        def iter_bytes(self):
            yield _png(np.full((512, 512, 3), 40, np.uint8))

    monkeypatch.setattr(analyzers.sentinel, "band_frame", band_frame)
    monkeypatch.setattr(analyzers.httpx, "stream", lambda method, url, **kwargs: Stream(url))
    saved = run(client, case, body)
    assert saved["status"] == "ready", saved
    assert read and set(read) == {sentinel.DEFAULT_MAXCC}
    assert pictures and all(f"MAXCC={sentinel.DEFAULT_MAXCC}" in url for url in pictures)


def test_a_frame_an_older_run_kept_under_a_ceiling_is_not_taken_for_a_whole_day():
    ceiling = Source(date="2026-05-04", maxcc=30)
    # an older run finds its own frames under the name it kept them by…
    assert analyzers._key(ceiling, 13, 1, 2, None, 4) == analyzers._key(ceiling, 13, 1, 2, None, 3)
    # …and a new run never reuses one, which may be the blank a ceiling made
    assert analyzers._key(ceiling, 13, 1, 2, None, 4) != analyzers._key(ceiling, 13, 1, 2, None)
    assert analyzers._key(ceiling, 13, 1, 2, "surface", 4) != analyzers._key(ceiling, 13, 1, 2, "surface")
    # a source that never had a ceiling read the whole day already
    whole = Source(date="2026-05-04", maxcc=100)
    assert analyzers._key(whole, 13, 1, 2, None, 4) == analyzers._key(whole, 13, 1, 2, None)
    # and the cache a sweep shares with the map is the day read whole
    assert analyzers.picture_cache_id(ceiling) == analyzers.picture_cache_id(whole)



def test_local_run_keeps_frames_and_review_without_network(client, scenario):
    case, body = scenario
    saved = run(client, case, body)
    assert saved["status"] == "ready", saved
    assert saved["engine_version"] == analyzers.ENGINE_VERSION
    assert saved["count"] == 1
    # two pictures to review and two band products measured
    assert len(saved["frames"]) == 4
    row = saved["results"][0]
    assert row["area"] > 0
    assert row["geometry"]["type"] == "Polygon"
    for frame in saved["frames"].values():
        assert case.resolve_inside(frame["path"]).is_file()
    assert row["review"] == "new"
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
    assert client.get(endpoint + "/preview").content.startswith(b"\x89PNG")
    promoted = client.post(endpoint + "/promote", json={"title": "Reviewed change"}).json()
    assert promoted["entity"]["type"] == "place"
    assert client.post(endpoint + "/promote", json={"title": "Again"}).json()["entity"]["id"] == promoted["entity"]["id"]
    # The picture shows the place it pins, as an edge its connections read, and once.
    picture = case.find_entity(attr="path", value=promoted["image"])
    shows = [link for link in case.links_of(picture["id"]) if link["type"] == "depicts"]
    assert [(link["from"], link["to"], link["provenance"]["by"]) for link in shows] == [
        (picture["id"], promoted["entity"]["id"], "compare")]
    # Promoted evidence survives deletion of the working analysis.
    assert client.delete(f"/api/cases/{case.id}/analysis/runs/{saved['id']}").status_code == 200
    assert case.resolve_inside(promoted["image"]).is_file()
    assert not case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}")).exists()


def test_a_candidate_says_how_strong_it_is_in_words_and_units(client, scenario):
    """A percentage of nothing in particular told nobody anything. A candidate
    now carries how far past its threshold it got, and the reading behind it."""
    case, body = scenario
    row = run(client, case, body)["results"][0]
    assert row["strength"] in {"weak", "clear", "strong"}
    assert row["margin"] >= 1
    # 0.30 → 0.10 red, 0.35 → 0.30 near, 0.40 → 0.20 short-wave: the reading is in percent
    assert 10 < row["measure"]["value"] < 25
    assert "signal_score" not in row and "confidence" not in row


def test_keeping_a_candidate_is_the_only_thing_that_reaches_the_case(client, scenario):
    """A sweep proposes; the analyst disposes, one candidate at a time."""
    case, body = scenario
    saved = run(client, case, body)
    row = saved["results"][0]
    places = [e for e in case.list_entities() if e["type"] == "place"]
    assert places == []          # candidates are not places until one is kept
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"

    # Keeping within a run leaves the case's entities alone.
    assert client.patch(endpoint, json={"review": "noted"}).json()["review"] == "noted"
    assert [e for e in case.list_entities() if e["type"] == "place"] == []

    # Keeping is one act: it records the verdict and files the pin together.
    kept = client.post(endpoint + "/promote", json={"title": "Kept candidate"}).json()
    assert client.get(endpoint.rsplit("/results/", 1)[0]).json()["results"][0]["review"] == "kept"
    assert len([e for e in case.list_entities() if e["type"] == "place"]) == 1

    # A kept candidate cannot be quietly re-triaged behind the pin's back.
    assert client.patch(endpoint, json={"review": "dismissed"}).status_code == 409

    # Undoing takes the pin away and gives the candidate back, the edge with them.
    picture = case.find_entity(attr="path", value=kept["image"])
    assert any(link["type"] == "depicts" for link in case.links_of(picture["id"]))
    assert client.delete(endpoint + "/promote").json()["result"]["review"] == "new"
    assert case.get_entity(kept["entity"]["id"]) is None
    assert not [link for link in case.list_links() if kept["entity"]["id"] in (link["from"], link["to"])]
    assert client.patch(endpoint, json={"review": "dismissed"}).status_code == 200
    assert client.get(endpoint + "/preview").status_code == 404


def test_undoing_a_keep_takes_its_picture_along_and_the_trash_brings_all_back(client, scenario):
    case, body = scenario
    saved = run(client, case, body)
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"

    # three hesitations leave nothing behind, however often the analyst changes their mind
    for _ in range(3):
        kept = client.post(endpoint + "/promote", json={"title": "Kept"}).json()
        undone = client.delete(endpoint + "/promote").json()
        assert case.find_entity(attr="path", value=kept["image"]) is None
        assert not case.resolve_inside(kept["image"]).exists()
    assert [e for e in case.list_entities() if e["type"] in ("place", "media")] == []

    group = undone["deleted"]["trash"]
    assert client.post(f"/api/cases/{case.id}/trash/{group}/restore").status_code == 200
    kinds = sorted(e["type"] for e in case.list_entities())
    assert "place" in kinds and "media" in kinds


def test_undoing_a_keep_leaves_a_picture_a_proof_was_made_from(client, scenario):
    case, body = scenario
    saved = run(client, case, body)
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{saved['results'][0]['id']}"
    kept = client.post(endpoint + "/promote", json={"title": "Kept"}).json()
    picture = case.find_entity(attr="path", value=kept["image"])
    proof = case.add_entity("proof", "Built on it", attrs={}, by="user")
    case.add_link(proof["id"], picture["id"], "derived-from", by="user")

    client.delete(endpoint + "/promote")

    assert case.find_entity(attr="path", value=kept["image"]) is not None


def test_a_candidate_preview_is_enlarged_so_its_pixels_can_be_read(client, scenario):
    """Legibility comes from whole-number nearest-neighbour zoom, not smoothing."""
    case, body = scenario
    saved = run(client, case, body)
    row = saved["results"][0]
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
    with Image.open(io.BytesIO(client.get(endpoint + "/preview").content)) as preview:
        box = row["parts"][0]["box"]
        crop = max(box[2], box[3]) + 2 * 20
        zoom = round(320 / crop)
        assert zoom > 1
        assert preview.width == 2 * (box[2] + 2 * 20) * zoom + 8
        # a band of labels above, and two lines of point and attribution below
        assert preview.height == (box[3] + 2 * 20) * zoom + 24 + 40


def test_a_candidate_picture_says_when_and_where_it_was_taken(client, scenario):
    """A pinned crop outlives the run that made it, so its face carries the
    date of each image and the point, not only the letters."""
    case, body = scenario
    saved = run(client, case, body)
    row = saved["results"][0]
    sources = [saved["frames"][key]["source"] for key in row["parts"][0]["frames"]]
    labels, foot = analyzers_api.preview_captions(saved, row, sources)
    lon, lat = row["coordinates"]
    assert labels == [f"A · {saved['input']['a']['date']}", f"B · {saved['input']['b']['date']}"]
    assert foot == [f"{lat:.5f}, {lon:.5f}", "Copernicus Sentinel data / Sentinel Hub"]
    assert analyzers_api.preview_captions(saved, row, sources[-1:])[0] == [saved["input"]["b"]["date"]]
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
    pinned = client.post(endpoint + "/promote", json={"title": "Checked"}).json()
    with Image.open(case.resolve_inside(pinned["image"])) as image:
        # the lines are drawn, not only composed: the foot holds ink
        foot_band = image.convert("RGB").crop((0, image.height - 40, image.width, image.height))
        assert (np.asarray(foot_band) != (20, 24, 32)).any()


def test_a_narrow_candidate_picture_still_has_room_for_its_label(client, scenario):
    """A radar pass names its time too, which is wider than a thin crop."""
    case, body = scenario
    saved = run(client, case, body)
    row = saved["results"][0]
    for key in row["parts"][0]["frames"]:
        saved["frames"][key]["source"] = {**saved["frames"][key]["source"], "provider": "sentinel1",
                                          "time": "16:32:10"}
    labels, _ = analyzers_api.preview_captions(saved, row, [saved["frames"][key]["source"]
                                                            for key in row["parts"][0]["frames"]])
    assert labels[0].endswith("16:32 UTC · radar")
    row["parts"][0]["box"] = [0, 0, 2, 40]
    with Image.open(io.BytesIO(analyzers_api.preview_bytes(case, saved, row))) as preview:
        crop = 2 + 2 * 20
        zoom = round(320 / (40 + 2 * 20))
        assert preview.width > 2 * crop * zoom + 8


def test_a_candidate_across_a_tile_edge_is_one_candidate_with_one_picture(client, scenario):
    """What crossed the seam used to come back as "evidence parts" to page
    through. It is one thing on the ground, so it is one candidate, and its
    preview is the two tiles laid side by side."""
    case, body = scenario
    z, x, y = SENTINEL_TILE
    body["zones"] = [zone(0.5, 0.1, 1.5, 0.9)]
    left, right = surface(), surface()
    left_after, right_after = surface(), surface()
    left_after[at(492, 200, 20, 20)] = code(0.30, 0.35, 0.40)
    right_after[at(0, 200, 20, 20)] = code(0.30, 0.35, 0.40)
    # the padding is the neighbour's pixels, as the provider serves it
    left_after[at(512, 200, PAD, 20)] = code(0.30, 0.35, 0.40)
    right_after[PAD + 200:PAD + 220, PAD - 20:PAD] = code(0.30, 0.35, 0.40)
    seed(body, left, left_after)
    seed(body, right, right_after, tile=(z, x + 1, y))
    saved = run(client, case, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1
    row = saved["results"][0]
    assert len(row["parts"]) == 2
    endpoint = f"/api/cases/{case.id}/analysis/runs/{saved['id']}/results/{row['id']}"
    response = client.get(endpoint + "/preview")
    assert response.status_code == 200
    with Image.open(io.BytesIO(response.content)) as preview:
        # 40 px of candidate across the seam plus the margins, twice, zoomed together
        crop = 40 + 2 * 20
        zoom = round(320 / crop)
        assert preview.width == 2 * crop * zoom + 8


def test_reading_saved_items_never_starts_jobs(client, scenario):
    case, body = scenario
    before = case.list_jobs()
    assert client.get("/api/compare/analyzers").status_code == 200
    for kind in ("zones", "followups", "runs"):
        assert client.get(f"/api/cases/{case.id}/analysis/{kind}").json() == []
    assert case.list_jobs() == before
    ring = Zone.model_validate(body["zones"][0]).ring()
    shared = client.post(f"/api/cases/{case.id}/analysis/areas", json={
        "name": "Port", "geometry": {"type": "Polygon", "coordinates": [ring + [ring[0]]]},
    }).json()
    area = client.post(f"/api/cases/{case.id}/analysis/zones", json={
        "title": "Port", "area_ids": [shared["id"]],
    }).json()
    follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()
    for kind, saved in (("zones", area), ("followups", follow)):
        assert client.get(f"/api/cases/{case.id}/analysis/{kind}/{saved['id']}").status_code == 200
    assert case.list_jobs() == before


def test_recipe_backup_and_duplicate_preserve_builtin(client):
    original = client.get("/api/compare/analyzers").json()["builtins"][0]
    custom = deepcopy(original)
    custom["name"] = "Weekly port check"
    saved = client.post("/api/compare/analyzers", json=custom).json()
    assert saved["id"] != original["id"]
    backup = client.get("/api/settings/export").json()
    client.delete(f"/api/compare/analyzers/{saved['id']}")
    restored = client.post("/api/settings/import", json=backup)
    assert restored.status_code == 200, restored.text
    catalogue = client.get("/api/compare/analyzers").json()
    assert catalogue["custom"] == [saved]
    assert catalogue["builtins"][0] == original


def test_cancelled_run_never_fetches_and_does_not_reappear(client, scenario):
    case, body = scenario
    saved = client.post(f"/api/cases/{case.id}/analysis/runs", json=body).json()
    url = f"/api/cases/{case.id}/analysis/runs/{saved['id']}"
    assert client.delete(url).status_code == 409
    assert client.post(url + "/cancel").json()["status"] == "cancelled"
    workqueue.drain(case)
    assert client.get(url).json()["frames"] == {}
    assert client.delete(url).status_code == 200
    assert client.get(url).status_code == 404


def test_runs_wait_their_turn_and_one_detection_is_never_swept_twice_at_once(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    first = client.post(f"{base}/runs", json=body).json()
    second = client.post(f"{base}/runs", json={**body, "title": "Another pass"}).json()
    assert [first["status"], second["status"]] == ["queued", "queued"]
    watch = client.post(f"{base}/followups", json={**body, "title": "Harbour"}).json()
    queued = client.post(f"{base}/followups/{watch['id']}/run")
    assert queued.status_code == 200, queued.text
    again = client.post(f"{base}/followups/{watch['id']}/run")
    assert again.status_code == 409
    assert "already queued or running" in again.json()["detail"]
    workqueue.drain(case)
    statuses = {row["id"]: row["status"] for row in client.get(f"{base}/runs").json()}
    assert statuses == {first["id"]: "ready", second["id"]: "ready", queued.json()["id"]: "ready"}
    # finished, the same detection can go again
    assert client.post(f"{base}/followups/{watch['id']}/run").status_code == 200


def test_a_saved_detection_runs_as_it_was_saved(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    watch = client.post(f"{base}/followups", json={**body, "title": "Harbour weekly"}).json()
    started = client.post(f"{base}/followups/{watch['id']}/run").json()
    assert started["title"] == "Harbour weekly"
    assert started["input"]["followup_id"] == watch["id"]
    assert Zone.model_validate(started["input"]["zones"][0]).ring() == Zone.model_validate(body["zones"][0]).ring()
    assert started["input"]["zones"][0]["id"] == watch["area_dates"][0]["area_id"]
    assert client.post(f"{base}/followups/abcdefabcdef/run").status_code == 404
    # A watch saved against Wayback reopens undated, and says so rather than failing later.
    analyzers.save(case, "followups", {**deepcopy(body), "title": "Old", "followup_id": None,
                                       "a": {"provider": "esri-wayback", "release": 3}})
    old = next(row for row in client.get(f"{base}/followups").json() if row["title"] == "Old")
    refused = client.post(f"{base}/followups/{old['id']}/run")
    assert refused.status_code == 422
    assert refused.json()["detail"] == "choose a reference date for each area"


def test_lists_say_what_each_item_looks_for_and_what_is_left_to_review(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    watch = client.post(f"{base}/followups", json={**body, "title": "Harbour"}).json()
    client.post(f"{base}/followups/{watch['id']}/run")
    workqueue.drain(case)
    [listed] = client.get(f"{base}/followups").json()
    assert listed["analyzer"] == body["recipe"]["name"] and listed["areas"] == 1
    # the shapes travel with the row, so the map can draw every watched area
    assert Zone.model_validate(listed["zones"][0]).ring() == Zone.model_validate(body["zones"][0]).ring()
    assert listed["date_rule"] == "manual" and listed["colour"] == body["recipe"]["colour"]
    [ran] = client.get(f"{base}/runs").json()
    assert ran["followup_id"] == watch["id"]
    assert ran["dates"] == [body["a"]["date"], body["b"]["date"]]
    assert ran["count"] == 1 and ran["to_review"] == 1 and ran["total"] == 1
    result = client.get(f"{base}/runs/{ran['id']}").json()["results"][0]
    client.patch(f"{base}/runs/{ran['id']}/results/{result['id']}", json={"review": "dismissed"})
    assert client.get(f"{base}/runs").json()[0]["to_review"] == 0


def test_a_sweep_lets_other_queued_work_through_between_its_tiles(client, scenario, monkeypatch):
    case, body = scenario
    monkeypatch.setattr(workqueue, "HANDLERS", dict(workqueue.HANDLERS))
    seen = []
    workqueue.register("probe", lambda c, job: seen.append(
        [row["status"] for row in analyzers.listing(c, "runs")]))
    client.post(f"/api/cases/{case.id}/analysis/runs", json=body)
    workqueue.enqueue(case, "probe", payload={})
    workqueue.drain(case)
    # queued after the sweep, settled while it was still running
    assert seen == [["running"]]
    assert analyzers.listing(case, "runs")[0]["status"] == "ready"


def test_a_candidate_can_be_kept_in_the_detections_view_without_touching_the_case(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    watch = client.post(f"{base}/followups", json={**body, "title": "Harbour", "note": "Weekly look"}).json()
    saved = run(client, case, {**body, "followup_id": watch["id"]})
    row = saved["results"][0]
    endpoint = f"{base}/runs/{saved['id']}/results/{row['id']}"
    before = len(case.list_entities())
    noted = client.patch(endpoint, json={"review": "noted"}).json()
    assert noted["review"] == "noted" and noted["entity_id"] is None
    # nothing reaches the case: no pin, no evidence file
    assert len(case.list_entities()) == before
    [found] = client.get(f"{base}/followups/{watch['id']}/findings").json()
    assert found["id"] == row["id"] and found["run_id"] == saved["id"]
    assert found["date"] == body["b"]["date"] and found["run_title"] == saved["title"]
    # a dismissal takes it back out of the findings
    client.patch(endpoint, json={"review": "dismissed"})
    assert client.get(f"{base}/followups/{watch['id']}/findings").json() == []
    assert client.post(endpoint + "/promote", json={"title": "Gone"}).status_code == 404
    # A later sweep can find the dismissed candidate again.
    saved = run(client, case, {**body, "followup_id": watch["id"], "run_anyway": True})
    endpoint = f"{base}/runs/{saved['id']}/results/{saved['results'][0]['id']}"
    client.post(endpoint + "/promote", json={"title": "Kept change"})
    [pinned] = client.get(f"{base}/followups/{watch['id']}/findings").json()
    assert pinned["review"] == "kept" and pinned["entity_id"]
    assert next(r for r in client.get(f"{base}/runs").json() if r["id"] == saved["id"])["marked"] == 1


def test_a_routine_relaunched_on_a_chosen_pass_asks_the_catalogue_nothing(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    routine = {**deepcopy(body), "title": "Harbour", "date_rule": "latest_previous"}
    watch = client.post(f"{base}/followups", json=routine).json()
    # `scenario` makes any network call an error, so a lookup here would fail the run
    started = client.post(f"{base}/followups/{watch['id']}/run", json={"date": body["b"]["date"]}).json()
    workqueue.drain(case)
    saved = client.get(f"{base}/runs/{started['id']}").json()
    assert saved["status"] == "ready", saved["message"]
    assert saved["input"]["b"]["date"] == body["b"]["date"]
    # the first run of a routine compares against the reference it was saved with
    assert saved["input"]["a"]["date"] == body["a"]["date"]


def test_a_second_pass_of_a_routine_compares_against_the_pass_before_it(client, scenario, monkeypatch):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    routine = {**deepcopy(body), "title": "Harbour", "date_rule": "latest_previous"}
    watch = client.post(f"{base}/followups", json=routine).json()
    client.post(f"{base}/followups/{watch['id']}/run", json={"date": body["b"]["date"]})
    workqueue.drain(case)
    later = "2026-05-18"
    seed_images({**body, "a": body["b"], "b": {**body["b"], "date": later}})
    second = client.post(f"{base}/followups/{watch['id']}/run", json={"date": later}).json()
    workqueue.drain(case)
    saved = client.get(f"{base}/runs/{second['id']}").json()
    assert saved["status"] == "ready", saved["message"]
    assert [saved["input"]["a"]["date"], saved["input"]["b"]["date"]] == [body["b"]["date"], later]


def test_a_routine_skips_current_areas_and_only_sweeps_the_area_with_a_new_pass(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    zones = [body["zones"][0], {**body["zones"][0], "id": "other", "name": "Other"}]
    routine = {**deepcopy(body), "title": "Two areas", "zones": zones, "date_rule": "latest_previous",
               "area_dates": [{"area_id": zone["id"], "a": body["a"],
                               "b": {**body["b"], "date": ""}, "date_rule": "latest_previous"}
                              for zone in zones]}
    watch = client.post(f"{base}/followups", json=routine).json()
    chosen = [{**pair, "b": {**pair["b"], "date": body["b"]["date"]}}
              for pair in watch["area_dates"]]
    first = client.post(f"{base}/followups/{watch['id']}/run", json={"area_dates": chosen}).json()
    workqueue.drain(case)
    assert client.get(f"{base}/runs/{first['id']}").json()["status"] == "ready"
    last = client.get(f"{base}/followups/{watch['id']}/last-passes").json()
    assert {source["date"] for source in last.values()} == {body["b"]["date"]}

    before = len(client.get(f"{base}/runs").json())
    unchanged = client.post(f"{base}/followups/{watch['id']}/run", json={"area_dates": chosen}).json()
    assert unchanged["status"] == "no_new_imagery" and "id" not in unchanged
    assert len(client.get(f"{base}/runs").json()) == before

    later = "2026-05-18"
    seed_images({**body, "a": body["b"], "b": {**body["b"], "date": later}})
    changed = [chosen[0], {**chosen[1], "b": {**chosen[1]["b"], "date": later}}]
    second = client.post(f"{base}/followups/{watch['id']}/run", json={"area_dates": changed}).json()
    assert [row["status"] for row in second["area_runs"]] == ["no_new_imagery", "pending"]
    workqueue.drain(case)
    saved = client.get(f"{base}/runs/{second['id']}").json()
    assert [row["status"] for row in saved["area_runs"]] == ["no_new_imagery", "ready"]
    assert saved["area_runs"][1]["a"]["date"] == body["b"]["date"]
    assert saved["area_runs"][0]["status"] == "no_new_imagery"
    assert saved["area_runs"][1]["status"] == "ready"


def test_a_comparison_rejects_a_date_that_is_not_before_b(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis/runs"
    later_a = {**deepcopy(body), "a": {**body["a"], "date": "2026-05-20"}}
    assert client.post(base, json=later_a).status_code == 422
    same_day = {**deepcopy(body), "a": {**body["a"], "date": body["b"]["date"]}}
    assert client.post(base, json=same_day).status_code == 422
    per_area = {**deepcopy(body), "area_dates": [{"area_id": body["zones"][0]["id"],
        "a": later_a["a"], "b": body["b"], "date_rule": "manual"}]}
    assert client.post(base, json=per_area).status_code == 422


def test_previous_pass_follows_image_order_after_a_later_backfill(client, scenario, monkeypatch):
    case, body = scenario
    ident = "abcdef123456"
    dates = ["2026-05-11", "2026-05-18", "2026-05-14"]
    monkeypatch.setattr(analyzers, "ready_runs", lambda *_: [
        ({"created_at": f"2026-06-0{index}T00:00:00Z"},
         {"area_runs": [{"area_id": body["zones"][0]["id"], "status": "ready",
                          "b": {**body["b"], "date": day}}]})
        for index, day in enumerate(dates, 1)
    ])
    query = RunInput.model_validate({**body, "followup_id": ident,
                                     "b": {**body["b"], "date": "2026-05-25"}})
    assert analyzers.previous_pass(case, query).date == "2026-05-18"


def test_a_detection_carries_what_it_is_for(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis"
    watch = client.post(f"{base}/followups", json={**body, "title": "Harbour", "note": "Vessels weekly"}).json()
    assert client.get(f"{base}/followups").json()[0]["note"] == "Vessels weekly"
    started = client.post(f"{base}/followups/{watch['id']}/run").json()
    assert started["input"]["note"] == "Vessels weekly"
    assert client.get(f"{base}/runs").json()[0]["note"] == "Vessels weekly"


def test_a_saved_routine_colour_can_change_without_losing_its_areas(client, scenario):
    case, body = scenario
    base = f"/api/cases/{case.id}/analysis/followups"
    watch = client.post(base, json=body).json()
    before = client.get(f"{base}/{watch['id']}").json()
    response = client.patch(f"{base}/{watch['id']}/colour", json={"colour": "#22d3ee"})
    assert response.status_code == 200, response.text
    changed = client.get(f"{base}/{watch['id']}").json()
    assert changed["recipe"]["colour"] == "#22d3ee"
    assert changed["area_dates"] == before["area_dates"]
    assert client.get(base).json()[0]["colour"] == "#22d3ee"
    assert client.patch(f"{base}/{watch['id']}/colour", json={"colour": "red"}).status_code == 422
    assert client.get(f"{base}/{watch['id']}").json()["recipe"]["colour"] == "#22d3ee"


def test_a_finished_one_pass_has_a_saved_display_colour(client, scenario):
    case, body = scenario
    finished = run(client, case, body)
    base = f"/api/cases/{case.id}/analysis/runs"
    original = finished["input"]["recipe"]["colour"]
    response = client.patch(f"{base}/{finished['id']}/colour", json={"colour": "#eab308"})
    assert response.status_code == 200, response.text
    changed = client.get(f"{base}/{finished['id']}").json()
    assert changed["display_colour"] == "#eab308"
    assert changed["input"]["recipe"]["colour"] == original
    assert client.get(base).json()[0]["colour"] == "#eab308"


def test_reexecution_uses_preserved_frames_after_tile_cache_loss(client, scenario, monkeypatch):
    case, body = scenario
    first = run(client, case, body)
    monkeypatch.setattr(tilecache, "get", lambda *args: None)
    second = run(client, case, body)
    assert second["status"] == "ready"
    assert first["id"] != second["id"]
    assert first["results"] == second["results"]
    assert first["input"] == second["input"]


def test_missing_offline_frames_fail_without_partial_results(client, scenario):
    case, body = scenario
    body["b"]["date"] = "2026-05-18"
    saved = run(client, case, body)
    assert saved["status"] == "failed"
    assert "offline" in saved["message"]
    assert saved["results"] == []


def test_tile_ceiling_and_source_validation_before_job_creation(client, scenario):
    case, body = scenario
    # The panel prices an area against these numbers, so they are published.
    catalogue = client.get("/api/compare/analyzers").json()
    assert catalogue["max_tiles"] == analyzers.MAX_TILES
    assert catalogue["grid"] == list(analyzers.GRID)
    big = deepcopy(body)
    big["zones"][0]["points"] = [[0, 0], [5, 5]]
    response = client.post(f"/api/cases/{case.id}/analysis/runs", json=big)
    assert response.status_code == 422
    assert "smaller" in response.text
    assert case.list_jobs() == []
    body["b"]["provider"] = "google"
    assert client.post(f"/api/cases/{case.id}/analysis/runs", json=body).status_code == 422


def test_detect_reads_copernicus_only_and_a_wayback_watch_asks_for_a_date(client, scenario):
    case, body = scenario
    old = deepcopy(body)
    old["a"] = {"provider": "esri-wayback", "release": 1}
    old["b"] = {"provider": "esri-wayback", "release": 2}
    response = client.post(f"/api/cases/{case.id}/analysis/runs", json=old)
    assert response.status_code == 422
    assert "dated Copernicus" in response.text
    assert case.list_jobs() == []


def test_overlapping_areas_keep_their_own_candidates(client, scenario):
    case, body = scenario
    first = run(client, case, body)
    body["zones"].append({**body["zones"][0], "id": "overlap"})
    second = run(client, case, body)
    assert second["count"] == 2 * first["count"]
    assert {r["area_id"] for r in second["results"]} == {"patch", "overlap"}
    assert second["total"] == 2 * first["total"]


def test_a_sweep_keeps_review_images_for_manual_candidates_and_prunes_unused_bands(client, scenario):
    """A missed detection can still be marked and cropped without fetching again."""
    case, body = scenario
    z, x, y = SENTINEL_TILE
    body["zones"] = [zone(0.1, 0.1, 1.9, 0.9)]
    seed_images(body, (z, x + 1, y), changed=False)
    saved = run(client, case, body)
    assert saved["status"] == "ready", saved
    assert saved["total"] == 2
    assert saved["count"] == 1
    assert len(saved["frames"]) == 6
    assert {tuple(record["tile"]) for record in saved["frames"].values() if record["index"] is not None} == {(z, x, y)}
    folder = case.resolve_inside(layout.analysis_assets_rel(f"runs-{saved['id']}"))
    assert {path.name for path in folder.iterdir()} == {
        record["path"].rsplit("/", 1)[1] for record in saved["frames"].values()
    }
    for row in saved["results"]:
        for part in row["parts"]:
            for key in part["frames"]:
                assert case.resolve_inside(saved["frames"][key]["path"]).is_file()


def test_a_run_reports_the_share_of_its_areas_that_had_imagery(client, scenario):
    case, body = scenario
    saved = run(client, case, body)
    assert saved["swept"] == 1.0


# -- models, catalogue and saved recipes ----------------------------------------------


@pytest.mark.parametrize("points", [[[0, 0], [0, 1]], [[179, 0], [-179, 1]], [[0, 86], [1, 87]]])
def test_invalid_areas_are_rejected(points):
    with pytest.raises(ValueError):
        Zone(id="zone", points=points)


def test_models_cannot_smuggle_executable_recipes():
    with pytest.raises(ValueError):
        Recipe(name="Bad", method="python", code="anything")
    assert config.DEFAULT_SETTINGS["analyzers"] == []


def test_a_recipe_saved_before_detect_went_copernicus_only_still_loads():
    old = {"id": "custom-1a2b3c4d5e6f", "name": "Harbour", "method": "colour",
           "providers": ["esri-wayback", "sentinel2"],
           "parameters": {"sensitivity": 40, "min_area": 20, "min_score": 0.2, "cleanup": 1,
                          "smoothing": 0, "normalize": True, "index": "ndvi",
                          "direction": "both", "ignore_clouds": True, "ignore_shadows": True,
                          "guess_clouds": False, "cloud_margin": 2, "merge_metres": 0}}
    recipe = Recipe.model_validate(old)
    assert recipe.method == "surface"
    assert recipe.parameters.sensitivity == 40 and recipe.parameters.cloud_margin == 2
    assert Recipe.model_validate({**old, "method": "water_objects"}).method == "vessels"
    assert "providers" not in recipe.model_dump()
    # areas once kept with an analyzer belong to a saved detection now
    kept = Recipe.model_validate({**old, "zones": [zone()]})
    assert "zones" not in kept.model_dump()


def test_every_method_publishes_sizes_and_words_for_its_reading():
    methods = {entry["id"]: entry for entry in METHODS}
    assert set(methods) == {"vessels", "hotspots", "structure", "spots", "surface", "index",
                            "sar-vessels", "sar-change", "rules"}
    # an analyzer of your own words its reading from its own first rule
    assert methods["rules"]["rules"] and methods["rules"]["measure"] == ""
    for entry in METHODS:
        assert set(entry["sizes"]) == {"small", "medium", "large", "all"}
        for size in entry["sizes"].values():
            Parameters(**size)          # every size is a valid set of parameters
        smaller, larger = entry["sizes"]["small"], entry["sizes"]["large"]
        assert smaller["min_area"] < larger["min_area"]
        # "All" drops nothing for its size, which is the answer to a mark that
        # falls between two bands and is found by neither.
        assert entry["sizes"]["all"]["min_area"] == 0
        assert entry["sizes"]["all"]["max_area"] == 0
        assert "{" in entry["measure"] or entry["rules"]
    # the fire test rejects cloud itself and radar sees through it; every other
    # method can use the mask
    assert [m for m, entry in methods.items() if not entry["clouds"]] == [
        "hotspots", "sar-vessels", "sar-change"]
    assert methods["vessels"]["single"] and methods["hotspots"]["single"]
    assert methods["sar-vessels"]["single"] and not methods["sar-change"]["single"]
    assert {m for m, entry in methods.items() if entry["sensor"] == "sentinel1"} == {
        "sar-vessels", "sar-change"}
    # a small target is never morphologically cleaned away
    assert all(entry["sizes"]["small"]["cleanup"] == 0 for entry in METHODS)


def test_builtins_cover_big_and_small_things_and_start_at_all_sizes():
    """A size picked without noticing drops what falls outside it, so a
    detection starts with none: Medium's 20 ha ceiling once dropped an
    airbase's worth of change."""
    ids = {recipe.id for recipe in BUILTINS}
    assert {"boats", "anomaly", "structures", "impacts", "large-change", "burn-scars",
            "vegetation-loss", "new-water"} <= ids
    # A flood is fields wide: at Medium the May 2023 Emilia-Romagna floods came
    # out in some 280 pieces, so the radar flood detector starts at Large.
    starts = {"radar-flood": "large"}
    for recipe in BUILTINS:
        size = SIZES[recipe.method][starts.get(recipe.id, "all")]
        assert {key: getattr(recipe.parameters, key) for key in size} == size, recipe.id
        assert len(recipe.description) < 200, recipe.id


def test_all_sizes_drops_the_limits_but_keeps_the_radar_averaging():
    for method, sizes in SIZES.items():
        assert sizes["all"]["min_area"] == sizes["all"]["max_area"] == 0, method
        # the panel tells the sizes apart by their numbers
        assert len({tuple(size.values()) for size in sizes.values()}) == 4, method
    assert SIZES["sar-change"]["all"]["smoothing"] == SIZES["sar-change"]["medium"]["smoothing"]


# -- vessels ---------------------------------------------------------------------------


@pytest.fixture
def copernicus(client, monkeypatch):
    monkeypatch.setattr(workqueue, "start_workers", False)
    ident = client.post("/api/cases", json={"name": "Copernicus detectors"}).json()["id"]
    case = Case.open(ident)

    def forbidden(*args, **kwargs):
        raise AssertionError("unexpected network")

    monkeypatch.setattr(analyzers.httpx, "stream", forbidden)
    monkeypatch.setattr(analyzers.sentinel, "band_frame", forbidden)
    return case


def test_vessels_are_found_and_breaking_waves_are_not(client, copernicus):
    """Wave crests are as bright as hulls in the near-infrared. Short-wave
    infrared is where they part: in the calibration scenes hulls stood 28 to 37
    deviations above their sea there, and 90% of wave crests under 3.5."""
    body = sentinel_input("boats")
    water = sea()
    hull(water, 120, 140, 6, 3)
    hull(water, 300, 220, 8, 4)
    hull(water, 200, 400, 6, 3, swir=False)   # a breaking wave
    seed(body, after=water)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 2, [r["coordinates"] for r in saved["results"]]
    assert {r["phenomenon"] for r in saved["results"]} == {"Vessel candidate"}
    for row in saved["results"]:
        assert row["strength"] == "strong"
        assert row["measure"]["value"] > 2        # times the water around it
    assert len(saved["frames"]) == 2   # the picture reviewed, and the bands measured


def test_a_hull_the_scene_classification_calls_cloud_is_still_a_hull(client, copernicus):
    """Sen2Cor tags white and red hulls as cloud; in Singapore it masked the tankers."""
    body = sentinel_input("boats")
    water = sea()
    hull(water, 250, 250, 8, 4)
    water[at(250, 250, 8, 4)][:, :, 3] = CLOUD
    seed(body, after=water)
    assert run(client, copernicus, body)["count"] == 1


def test_a_coastline_is_not_a_vessel(client, copernicus):
    body = sentinel_input("boats")
    water = sea()
    land = water[at(0, 300, 512, 212)]
    land[:, :, 0], land[:, :, 1], land[:, :, 2], land[:, :, 3] = 150, 150, 64, BARE
    # a bright headland sticking out into the water
    hull(water, 250, 290, 12, 10)
    seed(body, after=water)
    assert run(client, copernicus, body)["count"] == 0


def test_glint_does_not_turn_the_sea_into_land(client, copernicus):
    """Glint puts every band near 0.08 and leaves NDWI on zero, so an index read
    alone called two thirds of the Bab-el-Mandeb dry and the strait became one
    component of land. The classification is asked too, and either saying water
    is enough."""
    body = sentinel_input("boats")
    water = glinted_sea()
    hull(water, 200, 200, 8, 4)
    seed(body, after=water)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [r["coordinates"] for r in saved["results"]]


def test_sediment_flattens_the_index_and_the_classification_carries_it(client, copernicus):
    """Suspended matter does to the index what glint does: pushes it onto zero.

    The rule is not "this one scene", it is that a weak index is not a dry one.
    """
    body = sentinel_input("boats")
    water = sea()
    water[:, :, 2] = 120                                # NDWI ≈ -0.06, still water
    hull(water, 250, 250, 8, 4)
    seed(body, after=water)
    assert run(client, copernicus, body)["count"] == 1


def test_ground_the_classification_calls_water_is_still_ground(client, copernicus):
    """Sen2Cor calls deep shadow and dark ground water, and taking its word
    there would put vessel candidates on land. It is believed where the index is
    weak, never where the index plainly says dry."""
    body = sentinel_input("boats")
    desert = surface(0.30, 0.35, 0.30, WATER)           # the classification is wrong
    desert[:, :, 2] = 40                                # the index is not: NDWI ≈ -0.7
    roof = desert[at(250, 250, 8, 4)]
    roof[:, :, 0], roof[:, :, 1] = 255, 255             # something bright out there
    seed(body, after=desert)
    assert run(client, copernicus, body)["count"] == 0


def test_vessel_sweep_asks_for_one_date_and_never_for_a_reference(client, copernicus):
    body = sentinel_input("boats")
    water = sea()
    hull(water, 200, 200, 6, 3)
    seed(body, after=water)
    body["a"] = {"provider": "sentinel2", "date": "", "layer": "TRUE_COLOR", "maxcc": 30}
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["input"]["a"] == saved["input"]["b"]
    assert saved["count"] == 1


def test_local_contrast_reads_a_target_against_its_own_patch_of_sea():
    """The same hull, on calm water and on water twice as bright, reads the same."""
    rng = np.random.default_rng(7)
    calm = np.full((200, 200), 20.0) + rng.normal(0, 1.5, (200, 200))
    water = np.ones((200, 200), bool)
    readings = []
    for patch in (calm, calm + 120):
        empty, share, _ = analyzers.local_contrast(patch, water, 61, 11)
        assert share.min() > 0.99
        assert abs(empty[100, 100]) < 4
        target = patch.copy()
        target[99:102, 99:102] += 100
        contrast, _, _ = analyzers.local_contrast(target, water, 61, 11)
        readings.append(contrast[100, 100])
    assert min(readings) > 20
    assert abs(readings[0] - readings[1]) < 5


def test_local_contrast_treats_land_in_the_ring_as_missing_background():
    values = np.full((160, 160), 20.0)
    water = np.zeros((160, 160), bool)
    water[:, :40] = True
    _, share, _ = analyzers.local_contrast(values, water, 61, 11)
    assert share[80, 5] > 0.9      # open sea
    assert share[80, 120] == 0     # inland, no water in the ring at all
    assert share[80, 60] < 0.5     # a shoreline is not somewhere a ship can be


# -- hotspots ----------------------------------------------------------------------------


def test_hotspot_sweep_separates_fire_from_a_cloud_that_is_just_as_bright(client, copernicus):
    body = sentinel_input("anomaly")
    ground = fire_frame()
    flame(ground, 150, 160, 3, 3)
    flame(ground, 300, 300, 40, 40, b12=0.5, ratio=1.0)   # cloud: bright, ratios at one
    seed(body, after=ground)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [r["area"] for r in saved["results"]]
    row = saved["results"][0]
    assert row["phenomenon"] == "Hotspot candidate"
    assert row["area"] < 2000
    assert row["measure"]["value"] == pytest.approx(2.5, abs=0.05)
    z, x, y = SENTINEL_TILE
    west, north = analyzers.geographic((x + 150 / 512) / 2**z, (y + 160 / 512) / 2**z)
    assert abs(row["coordinates"][0] - west) < 0.001
    assert abs(row["coordinates"][1] - north) < 0.001


def test_hotspot_sweep_ignores_short_wave_below_the_published_floor(client, copernicus):
    body = sentinel_input("anomaly")
    ground = fire_frame()
    flame(ground, 150, 160, 3, 3, b12=analyzers.HOTSPOT_FLOOR - 0.02)
    seed(body, after=ground)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 0


def test_the_default_hotspot_ratio_is_the_published_one():
    recipe = next(r for r in BUILTINS if r.id == "anomaly")
    assert analyzers._scale(recipe.parameters.sensitivity, 1.0, 2.0) == pytest.approx(1.4)


# -- change between two dates -----------------------------------------------------------


def test_construction_is_ground_that_moved_the_same_way_in_every_band(client, copernicus):
    body = sentinel_input("structures")
    before, after = surface(0.20, 0.28, 0.32), surface(0.20, 0.28, 0.32)   # bare ground
    after[at(100, 100, 20, 20)] = code(0.33, 0.40, 0.45)        # new pad: brighter everywhere
    before[at(300, 300, 40, 40)] = code(0.05, 0.40, 0.18)       # a field that greened...
    after[at(300, 300, 40, 40)] = code(0.03, 0.60, 0.15)        # ...moved red and NIR apart
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1
    assert saved["results"][0]["measure"]["signed"] > 5


def test_burned_buildings_are_ground_that_went_dark_in_every_band(client, copernicus):
    """Soot, char and wreckage darken every band. A new roof brightens, the
    desert drifting a few percent stays under the line, and a burned field is
    Burn scars' to find."""
    body = sentinel_input("burned-buildings")
    before, after = surface(0.33, 0.39, 0.45, BARE), surface(0.33, 0.39, 0.45, BARE)
    after[at(100, 100, 12, 12)] = code(0.20, 0.24, 0.30, BARE)      # a burned hangar
    after[at(300, 100, 12, 12)] = code(0.45, 0.50, 0.55, BARE)      # a new bright roof
    after[at(100, 300, 30, 30)] = code(0.30, 0.36, 0.42, BARE)      # the desert drifting
    before[at(300, 300, 30, 30)] = code(0.05, 0.40, 0.18)           # a field...
    after[at(300, 300, 30, 30)] = code(0.04, 0.12, 0.16, BARE)      # ...that burned
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [(r["coordinates"], r["area"]) for r in saved["results"]]
    assert saved["results"][0]["measure"]["signed"] < -9


def test_small_spots_are_found_where_everything_around_them_held_still(client, copernicus):
    body = sentinel_input("impacts")
    before, after = surface(0.20, 0.30, 0.30), surface(0.20, 0.30, 0.30)
    after[at(100, 100, 2, 2)] = code(0.08, 0.12, 0.10)          # a burn mark two pixels wide
    after[at(300, 300, 120, 120)] = code(0.35, 0.40, 0.45)      # a whole field changed
    after[at(300, 300, 2, 2)] = code(0.05, 0.05, 0.05)          # a spot inside that field
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [r["coordinates"] for r in saved["results"]]
    row = saved["results"][0]
    assert row["measure"]["signed"] < 0
    assert row["area"] < 500


def test_a_granule_edge_is_not_a_spot(client, copernicus):
    """One date ends mid-tile, and that is not a change in the ground.

    The spot test measures a change against the change around it, so the ring
    it reads has to hold only pixels the sweep can measure. With nodata in it,
    a quiet tile cut by a granule edge produced a candidate the size of the cut.
    """
    before, after = surface(0.20, 0.30, 0.30), surface(0.20, 0.30, 0.30)
    after[:, 300:] = 0                                          # the granule stops here
    after[at(100, 100, 3, 3)] = code(0.05, 0.08, 0.08)           # a real mark beside it
    # Size All, so nothing is dropped for being too big to be a spot: the point
    # is that the seam raises no candidate at all, not that one is filtered out.
    body = sentinel_input("impacts", **SIZES["spots"]["all"])
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [(r["coordinates"], r["area"]) for r in saved["results"]]
    assert saved["results"][0]["area"] < 500


def test_a_cloud_edge_is_not_a_spot(client, copernicus):
    """A masked cloud is missing ground, exactly as nodata is."""
    before, after = surface(0.20, 0.30, 0.30), surface(0.20, 0.30, 0.30)
    after[:, 300:] = code(0.75, 0.80, 0.70, CLOUD)
    body = sentinel_input("impacts", **SIZES["spots"]["all"])
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 0, [(r["coordinates"], r["area"]) for r in saved["results"]]


def test_a_field_the_area_edge_cuts_is_not_a_spot(client, copernicus):
    """Past the area's edge nothing was measured, so it is not ground that held
    still. Counted as still, it made the sliver of a field left inside the edge
    look isolated, and lined an airbase's edge with candidates."""
    before, after = surface(0.20, 0.30, 0.30), surface(0.20, 0.30, 0.30)
    after[at(458, 150, 60, 120)] = code(0.35, 0.40, 0.45)       # a field, 3 px of it inside
    after[at(100, 100, 2, 2)] = code(0.08, 0.12, 0.10)          # a real mark
    body = sentinel_input("impacts", **SIZES["spots"]["all"])
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [(r["coordinates"], r["area"]) for r in saved["results"]]
    assert saved["results"][0]["area"] < 500


def test_smoothing_does_not_carry_a_granule_edge_into_the_ground_beside_it(client, copernicus):
    """The blur averages measured ground only; nodata read as a change bled
    into the pixels next to it and drew a line along the granule's end."""
    before, after = surface(0.20, 0.28, 0.32), surface(0.20, 0.28, 0.32)
    after[:, PAD + 300:] = 0
    body = sentinel_input("structures", min_area=0, max_area=0, cleanup=0, smoothing=3,
                          merge_metres=0)
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 0, [(r["coordinates"], r["area"]) for r in saved["results"]]


def candidates_of(mask):
    """The rows one tile's detection gives for `mask`, as a sweep builds them."""
    reading = analyzers.Reading(binary=mask.astype(np.uint8), stat=mask.astype(np.float32),
                                threshold=0.5)
    return analyzers._candidates(reading, "test", SENTINEL_TILE[1], SENTINEL_TILE[2], 0, [])


def test_merging_measures_the_gap_between_footprints_not_their_boxes():
    """A hollow mark's box holds the dots inside it, but its outline is far from
    them. Joined by boxes, and each join growing the box the next was tested
    against, an airbase's 667 marks became one candidate of 31 km²."""
    mask = np.zeros((512, 512), bool)
    mask[100:200, 100:104] = mask[100:104, 100:200] = mask[196:200, 100:200] = True   # a C, 650 m wide
    for x, y in ((140, 130), (160, 150), (140, 170), (170, 130), (170, 170)):
        mask[y:y + 3, x:x + 3] = True                           # dots 200 m inside it
    rows = candidates_of(mask)
    assert len(rows) == 6
    merged = analyzers.merge(rows, 20)
    assert len(merged) == 6, [row["area"] for row in merged]


def test_merging_joins_within_the_distance_and_not_past_it():
    mask = np.zeros((512, 512), bool)
    mask[100:104, 100:104] = mask[100:104, 106:110] = True       # 2 px apart, about 13 m
    mask[300:304, 100:104] = mask[300:304, 109:113] = True       # 5 px apart, about 33 m
    merged = analyzers.merge(candidates_of(mask), 20)
    assert sorted(len(row["parts"]) for row in merged) == [1, 1, 2]
    joined = next(row for row in merged if len(row["parts"]) == 2)
    assert joined["bbox"][3] == max(row["bbox"][3] for row in merged)   # the northern pair
    assert joined["geometry"]["type"] == "MultiPolygon" and len(joined["geometry"]["coordinates"]) == 2


def test_a_tile_edge_between_two_pieces_joins_them_even_at_zero():
    left = np.zeros((512, 512), bool)
    left[200:220, 492:512] = True
    right = np.zeros((512, 512), bool)
    right[200:220, 0:20] = True
    right[400:404, 0:4] = True                                   # touches nothing
    z, x, y = SENTINEL_TILE
    rows = candidates_of(left) + analyzers._candidates(
        analyzers.Reading(binary=right.astype(np.uint8), stat=right.astype(np.float32), threshold=0.5),
        "test", x + 1, y, 1, [])
    piece = rows[0]["area"]
    merged = analyzers.merge(rows, 0)
    assert sorted(round(row["area"] / piece, 2) for row in merged) == [0.04, 2.0]


def test_a_mark_wider_than_its_window_still_reads_its_own_contrast(client, copernicus):
    """A median box the size of the target takes the target for its background.

    The background is read from a ring with a hole in it instead, so a 90 m mark
    in the desert measures what it really moved. Medium then drops it for its
    size, with nothing to show for it — which is what All is for.
    """
    ground = surface(0.37, 0.40, 0.55)
    marked = surface(0.37, 0.40, 0.55)
    marked[at(200, 200, 10, 10)] = code(0.29, 0.30, 0.45)

    body = sentinel_input("impacts", **SIZES["spots"]["medium"])
    seed(body, ground, marked)
    assert run(client, copernicus, body)["count"] == 0

    body = sentinel_input("impacts", **SIZES["spots"]["all"])
    seed(body, ground, marked)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1, [r["area"] for r in saved["results"]]
    row = saved["results"][0]
    assert row["area"] > 800                                   # too big for Small
    assert row["measure"]["signed"] < -5                       # and it moved 8-10%


def test_a_burn_has_to_end_dark_and_a_dried_pasture_does_not(client, copernicus):
    """Dry soil has a negative burn ratio too; char is what is dark."""
    body = sentinel_input("burn-scars")
    before, after = index_frame(0.5), index_frame(0.5)
    after[at(100, 100, 40, 40)] = [index_byte(-0.3), 0, 0, BARE + DARK]   # burned
    after[at(300, 300, 40, 40)] = [index_byte(-0.1), 0, 0, BARE]          # dried, still bright
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1
    row = saved["results"][0]
    assert row["measure"]["before"] == pytest.approx(0.5, abs=0.02)
    assert row["measure"]["after"] == pytest.approx(-0.3, abs=0.02)


def test_an_index_loss_has_to_start_from_something_there(client, copernicus):
    """NDVI noise over bare ground is not vegetation loss."""
    body = sentinel_input("vegetation-loss")
    before, after = index_frame(0.1), index_frame(0.1)
    before[at(100, 100, 40, 40)] = [index_byte(0.7), 0, 0, VEGETATION]
    after[at(100, 100, 40, 40)] = [index_byte(0.2), 0, 0, BARE]            # cleared
    before[at(300, 300, 40, 40)] = [index_byte(0.35), 0, 0, BARE]          # never green
    after[at(300, 300, 40, 40)] = [index_byte(-0.1), 0, 0, BARE]
    before[at(100, 300, 40, 40)] = [index_byte(0.8), 0, 0, VEGETATION]     # still green
    after[at(100, 300, 40, 40)] = [index_byte(0.45), 0, 0, VEGETATION]
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] == 1


def test_a_whole_tile_that_burned_is_not_taken_for_a_change_in_light(client, copernicus):
    """The overall shift between passes is taken out, but only up to 3%: a burn
    that covers most of the tile moves the median itself."""
    body = sentinel_input("large-change", min_area=0, max_area=0)
    before = surface(0.10, 0.30, 0.25)
    after = surface(0.06, 0.12, 0.12)
    after[at(0, 0, 100, 512)] = code(0.10, 0.30, 0.25)
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["status"] == "ready", saved
    assert saved["count"] >= 1
    assert max(row["area"] for row in saved["results"]) > 1_000_000


def test_candidates_come_strongest_first(client, copernicus):
    body = sentinel_input("large-change", min_area=0, max_area=0, cleanup=0, merge_metres=0)
    before, after = surface(), surface()
    after[at(50, 50, 20, 20)] = code(0.19, 0.39, 0.29)    # a modest change
    after[at(300, 300, 20, 20)] = code(0.40, 0.45, 0.50)  # a large one
    seed(body, before, after)
    saved = run(client, copernicus, body)
    margins = [row["margin"] for row in saved["results"]]
    assert len(margins) == 2 and margins == sorted(margins, reverse=True)
    assert saved["results"][0]["strength"] == "strong"


def test_direction_keeps_only_the_way_that_was_asked_for(client, copernicus):
    body = sentinel_input("large-change", min_area=0, max_area=0, direction="loss")
    before, after = surface(), surface()
    after[at(50, 50, 20, 20)] = code(0.40, 0.50, 0.50)    # brighter
    after[at(300, 300, 20, 20)] = code(0.02, 0.05, 0.02)  # darker
    seed(body, before, after)
    saved = run(client, copernicus, body)
    assert saved["count"] == 1
    assert saved["results"][0]["coordinates"][0] > body["zones"][0]["points"][0][0]


# -- sky ----------------------------------------------------------------------------------


def _sky_body(**parameters):
    return RunInput.model_validate(sentinel_input("large-change", **parameters))


def test_a_cloud_takes_its_unsure_edge_but_a_small_bright_tag_is_not_cloud():
    frame = surface()
    frame[at(100, 100, 20, 20)][:, :, 3] = CLOUD                 # 1.8 ha: a white roof
    frame[at(250, 250, 120, 120)][:, :, 3] = CLOUD               # a real cloud
    frame[at(240, 250, 10, 120)][:, :, 3] = UNSURE               # its thin western edge
    frame[at(20, 20, 10, 10)][:, :, 3] = UNSURE                  # an unsure pixel on its own
    metres = 6.7
    cloud, _ = analyzers.sky(frame, "2026-05-11", 45.5, metres)
    core = cloud[PAD:-PAD, PAD:-PAD]
    assert not core[100:120, 100:120].any()
    assert core[250:370, 250:370].all()
    assert core[250:370, 240:250].all()
    assert not core[20:30, 20:30].any()


def test_a_shadow_the_classification_missed_is_found_away_from_the_sun():
    """In May at 45°N the satellite sees the sun in the south-east, so a cloud's
    shadow falls to its north-west, on ground dark enough to be shaded."""
    frame = surface()
    frame[at(300, 300, 80, 80)][:, :, 3] = CLOUD
    shaded = frame[at(200, 180, 90, 90)]
    shaded[:, :, 3] = VEGETATION + DARK                          # north-west: shadow
    darkness = frame[at(420, 420, 60, 60)]
    darkness[:, :, 3] = VEGETATION + DARK                        # south-east: just dark ground
    _, shadow = analyzers.sky(frame, "2026-05-11", 45.5, 6.7)
    core = shadow[PAD:-PAD, PAD:-PAD]
    assert core[200:270, 200:270].any()
    assert not core[420:480, 420:480].any()


def test_a_shadow_the_classification_called_water_is_still_a_shadow():
    """Sen2Cor reads a deep cloud shadow as water, and a cast that spares water
    then finds none of it. A second pass settles it: water is water when both
    dates say so, and a shadow is what only one of them calls water."""
    frame = surface()
    frame[at(300, 300, 80, 80)][:, :, 3] = CLOUD
    frame[at(200, 180, 45, 90)][:, :, 3] = WATER + DARK          # shadow, read as water
    frame[at(245, 180, 45, 90)][:, :, 3] = WATER + DARK          # a real lake
    clear = surface()
    clear[at(245, 180, 45, 90)][:, :, 3] = WATER                 # the lake, on the other date
    _, alone = analyzers.sky(frame, "2026-05-11", 45.5, 6.7)
    _, paired = analyzers.sky(frame, "2026-05-11", 45.5, 6.7, clear)
    assert not alone[PAD:-PAD, PAD:-PAD][200:270, 200:245].any()
    assert paired[PAD:-PAD, PAD:-PAD][200:270, 200:245].any()
    assert not paired[PAD:-PAD, PAD:-PAD][200:270, 245:290].any()


def test_the_sun_is_where_the_satellite_saw_it():
    """Checked against the angle bands of real scenes, to within a few degrees."""
    for day, lat, azimuth, zenith in [("2026-09-08", 12.6, 108.2, 20.4),
                                      ("2026-08-12", 1.24, 57.6, 26.5),
                                      ("2026-09-13", 39.24, 157.6, 37.8),
                                      ("2026-09-12", -9.79, 61.0, 27.5)]:
        found_azimuth, found_zenith = analyzers.sun_position(day, lat)
        assert abs(found_azimuth - azimuth) < 6
        assert abs(found_zenith - zenith) < 3


def test_the_cloud_margin_grows_the_mask_past_the_classified_edge():
    body = _sky_body(cloud_margin=3)
    frame = surface()
    frame[at(200, 200, 100, 100)][:, :, 3] = CLOUD
    blocked = analyzers.weather_mask([frame, frame], ["2026-05-04", "2026-05-11"], 45.5, 6.7,
                                     body.recipe.parameters)
    core = blocked[PAD:-PAD, PAD:-PAD]
    assert core[197:303, 197:303].all()
    assert not core[190:196, 190:196].any()


def test_turning_both_switches_off_masks_nothing():
    body = _sky_body(ignore_clouds=False, ignore_shadows=False)
    frame = surface()
    frame[:, :, 3] = CLOUD
    assert analyzers.weather_mask([frame], ["2026-05-11"], 45.5, 6.7,
                                  body.recipe.parameters) is None


def test_a_change_under_cloud_on_either_date_is_not_a_change(client, copernicus):
    body = sentinel_input("large-change", min_area=0, max_area=0, cleanup=0)
    before, after = surface(), surface()
    after[at(200, 200, 120, 120)] = code(0.45, 0.50, 0.45, sky=CLOUD)
    seed(body, before, after)
    assert run(client, copernicus, body)["count"] == 0


# -- follow-ups and date rules -------------------------------------------------------------


def test_named_followup_freezes_input_and_previous_date(client, scenario, monkeypatch):
    case, body = scenario
    follow = client.post(f"/api/cases/{case.id}/analysis/followups", json=body).json()
    body["followup_id"] = follow["id"]
    previous = run(client, case, body)
    client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
    monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
        {"date": "2026-05-18", "cloud": 5.0, "granules": 1, "coverage": 1.0},
    ], "truncated": False})
    newer = {**body, "offline": False, "date_rule": "latest_previous"}
    resolved = analyzers.resolve_dates(case, RunInput.model_validate(newer))
    assert resolved.a.date == previous["input"]["b"]["date"] and resolved.b.date == "2026-05-18"
    changed = deepcopy(body)
    changed["zones"][0]["name"] = "New name"
    assert client.put(f"/api/cases/{case.id}/analysis/followups/{follow['id']}", json=changed).status_code == 200
    assert analyzers.read(case, "runs", previous["id"])["input"]["zones"][0]["name"] == "Patch"


def _rule(body, rule="latest_reference"):
    return {**deepcopy(body), "offline": False, "date_rule": rule}


def test_an_automatic_date_rule_takes_the_newest_pass_that_covers_the_whole_area(
    client, scenario, monkeypatch
):
    """The old rule asked about each area's *centre*, which a swath can reach
    while missing most of the shape around it. Picking that date sweeps nodata."""
    case, body = scenario
    client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
    asked = {}

    def acquisitions(instance, rings, start, end, collection="sentinel2", **kwargs):
        asked.update(instance=instance, rings=rings, start=start, end=end)
        return {"dates": [
            {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},
            {"date": "2026-05-11", "cloud": 5.0, "granules": 2, "coverage": 1.0},
            {"date": "2026-05-04", "cloud": 5.0, "granules": 1, "coverage": 1.0},
        ], "truncated": False}

    monkeypatch.setattr(analyzers.sentinel, "acquisitions", acquisitions)
    resolved = analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))
    # the newest is 2026-05-20 and it reaches 61% of the area, so it is not it
    assert resolved.b.date == "2026-05-11"
    # one lookup for the whole set, not one per area
    assert len(asked["rings"]) == 1


def test_an_automatic_date_rule_says_how_far_the_best_pass_reached(
    client, scenario, monkeypatch
):
    case, body = scenario
    client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
    monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
        {"date": "2026-05-20", "cloud": 5.0, "granules": 1, "coverage": 0.61},
    ], "truncated": False})
    with pytest.raises(ValueError) as raised:
        analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))
    # naming the number turns "it failed" into "pick the dates by hand"
    assert "61%" in str(raised.value)


def test_an_automatic_date_rule_still_honours_the_cloud_ceiling(client, scenario, monkeypatch):
    case, body = scenario
    client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
    monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
        {"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},
        {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},
    ], "truncated": False})
    notes = []
    resolved = analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)), notes=notes)
    assert resolved.b.date == "2026-05-11"
    assert notes == ["Skipped 2026-05-20 (80% cloud, limit 30%); using 2026-05-11."]


def test_cloudy_latest_pass_is_explained_when_clear_imagery_has_only_partial_cover(
    client, scenario, monkeypatch
):
    case, body = scenario
    client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
    monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
        {"date": "2026-05-20", "cloud": 80.0, "granules": 1, "coverage": 1.0},
        {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 0.61},
    ], "truncated": False})
    with pytest.raises(ValueError, match="latest pass 2026-05-20 has 80% cloud"):
        analyzers.resolve_dates(case, RunInput.model_validate(_rule(body)))


def test_an_automatic_comparison_rejects_a_pass_before_its_fixed_reference(client, scenario, monkeypatch):
    case, body = scenario
    client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})
    monkeypatch.setattr(analyzers.sentinel, "acquisitions", lambda *a, **k: {"dates": [
        {"date": "2026-05-11", "cloud": 5.0, "granules": 1, "coverage": 1.0},
    ], "truncated": False})
    asked = RunInput.model_validate({**_rule(body), "a": {**body["a"], "date": "2026-05-20"},
                                     "b": {**body["b"], "date": ""}})
    _, outcomes = analyzers.prepare_areas(case, asked)
    assert outcomes[0]["status"] == "failed"
    assert "date A must be before date B" in outcomes[0]["message"]
    response = client.post(f"/api/cases/{case.id}/analysis/runs", json=asked.model_dump())
    assert response.status_code == 422
    assert "date A must be before date B" in response.json()["detail"]
    assert client.get(f"/api/cases/{case.id}/analysis/runs").json() == []


def test_band_products_are_padded_and_keyed_apart_from_older_layouts():
    body = RunInput.model_validate(sample_input())
    z, x, y = SENTINEL_TILE
    picture = analyzers._key(body.b, z, x, y, None)
    product = analyzers._key(body.b, z, x, y, "surface")
    assert picture != product
    assert analyzers.product_cache_id(body.b, "surface").endswith(f"~surface~v{analyzers.PRODUCT_VERSION}")
    assert EDGE == 512 + 2 * analyzers.PAD
    assert WATER == analyzers.SCL_WATER


def test_a_deleted_area_leaves_its_groups_and_comes_back_with_a_restore(client, scenario):
    """Groups are not guarded like routines: deleting an area they hold is allowed,
    and the group stops counting it rather than listing a dead id."""
    case, body = scenario
    ring = Zone.model_validate(body["zones"][0]).ring()
    shared = client.post(f"/api/cases/{case.id}/analysis/areas", json={
        "name": "Port", "geometry": {"type": "Polygon", "coordinates": [ring + [ring[0]]]},
    }).json()
    client.post(f"/api/cases/{case.id}/analysis/zones", json={"title": "Coast", "area_ids": [shared["id"]]})

    assert client.delete(f"/api/cases/{case.id}/analysis/areas/{shared['id']}").status_code == 200
    [group] = client.get(f"/api/cases/{case.id}/analysis/zones").json()
    assert (group["area_ids"], group["areas"]) == ([], 0)

    trash = client.get(f"/api/cases/{case.id}/trash").json()
    [entry] = trash["groups"]
    assert client.post(f"/api/cases/{case.id}/trash/{entry['id']}/restore").status_code == 200
    [group] = client.get(f"/api/cases/{case.id}/analysis/zones").json()
    assert group["area_ids"] == [shared["id"]]


# -- areas as a file, handed to another analyst ---------------------------------------

RING = [[2.29, 48.855], [2.3, 48.855], [2.3, 48.862], [2.29, 48.862], [2.29, 48.855]]
GROUND = {"type": "Polygon", "coordinates": [RING]}


def ground_case(client, name="Ground"):
    return client.post("/api/cases", json={"name": name}).json()["id"]


def put_area(client, case_id, name, colour="#38bdf8"):
    saved = client.post(f"/api/cases/{case_id}/analysis/areas",
                        json={"name": name, "colour": colour, "geometry": GROUND})
    assert saved.status_code == 200, saved.text
    return saved.json()


def put_group(client, case_id, title, areas):
    saved = client.post(f"/api/cases/{case_id}/analysis/zones",
                        json={"title": title, "area_ids": [area["id"] for area in areas]})
    assert saved.status_code == 200, saved.text
    return saved.json()


def test_a_shared_group_carries_its_ground_its_colours_and_its_folder(client):
    case_id = ground_case(client)
    first, second = put_area(client, case_id, "Pump 1"), put_area(client, case_id, "Pump 2", "#f6a81a")
    group = put_group(client, case_id, "Pumping stations", [first, second])

    answer = client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}/share")
    assert answer.status_code == 200, answer.text
    assert answer.headers["content-disposition"] == 'attachment; filename="azimut-areas-pumping-stations.json"'
    file = answer.json()
    assert (file["azimut"], file["version"], file["app"]) == ("azimut-areas", 1, __version__)
    assert [area["name"] for area in file["areas"]] == ["Pump 1", "Pump 2"]
    # what no generic map format keeps: the colours and the folder they sit in
    assert [area["colour"] for area in file["areas"]] == ["#38bdf8", "#f6a81a"]
    assert file["groups"] == [{"title": "Pumping stations", "area_ids": [first["id"], second["id"]]}]
    # this case's own bookkeeping about redrawn shapes stays behind
    assert "pending_review" not in str(file)

    alone = client.get(f"/api/cases/{case_id}/analysis/areas/{first['id']}/share").json()
    assert [area["name"] for area in alone["areas"]] == ["Pump 1"] and alone["groups"] == []


def test_imported_ground_is_filed_afresh_and_never_over_what_is_here(client):
    case_id = ground_case(client)
    first, second = put_area(client, case_id, "Pump 1"), put_area(client, case_id, "Pump 2")
    group = put_group(client, case_id, "Pumping stations", [first, second])
    file = client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}/share").json()

    answer = client.post(f"/api/cases/{case_id}/analysis/areas/import", json=file)
    assert answer.status_code == 200, answer.text
    body = answer.json()
    assert [area["name"] for area in body["areas"]] == ["Pump 1 2", "Pump 2 2"]
    assert body["groups"][0]["title"] == "Pumping stations 2"
    assert body["renamed"] == ["Pump 1", "Pump 2", "Pumping stations"]
    # The ids in a file only join a group to its ground; the case mints its own.
    assert body["groups"][0]["area_ids"] == [area["id"] for area in body["areas"]]
    assert not {area["id"] for area in body["areas"]} & {first["id"], second["id"]}
    assert client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}").json()["area_ids"] == [
        first["id"], second["id"]]

    # The point of the file: the same ground in somebody else's case.
    other = ground_case(client, "Second case")
    landed = client.post(f"/api/cases/{other}/analysis/areas/import", json=file).json()
    assert [area["name"] for area in landed["areas"]] == ["Pump 1", "Pump 2"]
    assert landed["renamed"] == [] and landed["groups"][0]["title"] == "Pumping stations"
    assert landed["groups"][0]["area_ids"] == [area["id"] for area in landed["areas"]]


def test_a_file_that_is_not_areas_is_named_back_rather_than_blankly_refused(client):
    case_id = ground_case(client)
    url = f"/api/cases/{case_id}/analysis/areas/import"
    backup = client.post(url, json=client.get("/api/settings/export").json())
    assert backup.status_code == 422 and "settings backup" in backup.text
    analyzer = client.post(url, json={"azimut": "azimut-analyzer", "version": 1, "recipe": {}})
    assert analyzer.status_code == 422 and "analyzer library" in analyzer.text
    assert "not Azimut areas" in client.post(url, json={"a": 1}).text
    newer = client.post(url, json={"azimut": "azimut-areas", "version": 2, "areas": [{}]})
    assert newer.status_code == 422 and "newer format" in newer.text
    empty = client.post(url, json={"azimut": "azimut-areas", "version": 1, "areas": []})
    assert empty.status_code == 422 and "no area" in empty.text
    torn = client.post(url, json={"azimut": "azimut-areas", "version": 1,
                                  "areas": [{"name": "Open", "geometry": {"type": "Polygon",
                                                                          "coordinates": [RING[:2]]}}]})
    assert torn.status_code == 422 and "could not be read" in torn.text
    # A file this build cannot make sense of leaves the case exactly as it was.
    assert client.get(f"/api/cases/{case_id}/analysis/areas").json() == []


def test_areas_from_a_newer_build_land_and_say_what_went_unread(client):
    case_id = ground_case(client)
    file = {"azimut": "azimut-areas", "version": 1, "app": "9.9.9",
            "areas": [{"id": "aaaaaaaaaaaa", "name": "Pump 1", "colour": "#38bdf8",
                       "geometry": GROUND, "elevation": 42}],
            "groups": [{"title": "Stations", "area_ids": ["aaaaaaaaaaaa"], "legend": "by depth"}]}
    answer = client.post(f"/api/cases/{case_id}/analysis/areas/import", json=file)
    assert answer.status_code == 200, answer.text
    body = answer.json()
    assert body["ignored_fields"] == ["elevation", "legend"]
    assert body["written_by"] == "9.9.9"
    assert body["areas"][0]["geometry"] == GROUND
    assert body["groups"][0]["area_ids"] == [body["areas"][0]["id"]]


def test_a_group_shares_the_ground_it_still_has(client):
    case_id = ground_case(client)
    first, second = put_area(client, case_id, "Pump 1"), put_area(client, case_id, "Pump 2")
    group = put_group(client, case_id, "Pumping stations", [first, second])
    assert client.delete(f"/api/cases/{case_id}/analysis/areas/{second['id']}").status_code == 200

    file = client.get(f"/api/cases/{case_id}/analysis/zones/{group['id']}/share").json()
    # A deleted area stays named in its group so the Trash can put it back, and
    # has no ground to send in the meantime.
    assert [area["name"] for area in file["areas"]] == ["Pump 1"]
    assert file["groups"][0]["area_ids"] == [first["id"]]
    landed = client.post(f"/api/cases/{ground_case(client, 'Third')}/analysis/areas/import", json=file).json()
    assert len(landed["areas"]) == 1 and landed["groups"][0]["area_ids"] == [landed["areas"][0]["id"]]