"""Tests for the two KEYLESS live-data adapters.

    orchestrator/overpass.py     OpenStreetMap business counts — no key, no signup
    orchestrator/open_meteo.py   current + 7-day forecast      — no key, no signup

The required cases:

  (a) Overpass with a mocked successful response writes cited claims and produces
      one signal per category that has results
  (b) Overpass with a mocked 429 writes ZERO claims and reports RATE LIMITED
  (c) Open-Meteo success writes cited claims
  (d) Open-Meteo failure writes zero claims and reports DEGRADED
  (e) Neither adapter ever raises on a network failure

No test touches the network: every HTTP call is monkeypatched at the adapter's
own ``_http`` seam, so the assertions are about the code's behaviour on a body
we control — never about what the internet happened to return today.
"""

from __future__ import annotations

import json
import os
import re
import tempfile
import time
import urllib.error

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-keyless-test-")
os.environ.setdefault("JARVIS_DB", os.path.join(_TMP, "test.db"))
os.environ.setdefault("JARVIS_MEMORY_DB", os.path.join(_TMP, "memory.db"))

from orchestrator import live_data  # noqa: E402
from orchestrator import live_ingest  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import open_meteo  # noqa: E402
from orchestrator import overpass  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_stores():
    """Fresh sqlite files + fresh live-data/ingest memory for every test."""
    for path in (os.environ["JARVIS_DB"], os.environ["JARVIS_MEMORY_DB"]):
        for suffix in ("", "-wal", "-shm"):
            try:
                os.remove(path + suffix)
            except FileNotFoundError:
                pass
        os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    init_db()
    memory.init_db()
    live_data.reset_for_tests()
    live_ingest.reset_for_tests()
    # The Overpass adapter caches successful per-category counts in-process for
    # CACHE_TTL_SECONDS; without this a later test would be served a previous
    # test's mocked body and never touch its own monkeypatched ``_http``.
    overpass.reset_cache()
    yield
    live_data.reset_for_tests()
    live_ingest.reset_for_tests()
    overpass.reset_cache()


def _claim_count() -> int:
    conn = memory.connect()
    try:
        return int(conn.execute("SELECT COUNT(*) AS n FROM claims").fetchone()["n"])
    finally:
        conn.close()


def _all_claims() -> list[dict]:
    conn = memory.connect()
    try:
        return [dict(r) for r in conn.execute("SELECT * FROM claims").fetchall()]
    finally:
        conn.close()


def _probe_only(source_id: str) -> dict:
    """Probe ONE adapter and record it, so a test never touches the network.

    ``live_data.probe_all()`` would also fire the keyed adapters' real requests;
    the tests only need the source under test to be the current capture.
    """
    # Seed first, exactly like app startup: ``seed_if_empty`` only loads the
    # 2026-11-18 captures when the log is completely empty, so probing before
    # seeding would leave the keyed adapters reporting "never probed".
    live_data.seed_if_empty()
    entry = live_data._probe_one(live_data.SOURCE_BY_ID[source_id])
    live_data._record_capture(entry)
    return entry


def _ingest(sources=None) -> dict:
    conn = connect()
    try:
        return live_ingest.ingest_live_signals(conn, sources=sources)
    finally:
        conn.close()


# ---------------------------------------------------------------------------
# fixtures: a real-shaped Overpass body and a real-shaped Open-Meteo body
# ---------------------------------------------------------------------------
def _osm(node_id, name, tags, lat=43.15, lon=-77.60):
    return {"type": "node", "id": node_id, "lat": lat, "lon": lon,
            "tags": dict({"name": name}, **tags)}


def _overpass_elements():
    """Six categories, with one business tagged in TWO categories.

    ``Rochester Heating & Air`` carries both ``shop=hvac`` and ``craft=plumber``,
    so it must be counted once — under the FIRST category in CATEGORIES order
    (HVAC contractor) — and the plumber count must not include it.
    """
    return [
        # HVAC contractor: 6 distinct businesses
        _osm(1, "Rochester Heating & Air", {"shop": "hvac", "craft": "plumber",
                                            "addr:housenumber": "12",
                                            "addr:street": "Main St",
                                            "addr:city": "Rochester",
                                            "addr:postcode": "14604"}),
        _osm(2, "Genesee HVAC", {"shop": "hvac"}),
        _osm(3, "Lake Effect Heating", {"craft": "hvac"}),
        _osm(4, "Flower City Comfort", {"shop": "hvac"}),
        _osm(5, "Brighton Air", {"shop": "hvac"}),
        _osm(6, "Irondequoit Heating", {"shop": "hvac"}),
        # plumber: 2 more (the dual-tagged one above is NOT counted here)
        _osm(7, "Duffy Plumbing", {"craft": "plumber"}),
        _osm(8, "Rochester Pipeworks", {"craft": "plumber"}),
        # landscaper: 5 (craft=gardener + shop=garden_centre)
        _osm(9, "Green Thumb Gardens", {"craft": "gardener"}),
        _osm(10, "Honeoye Landscaping", {"craft": "gardener"}),
        _osm(11, "Pittsford Yards", {"craft": "gardener"}),
        _osm(12, "Bristol Nursery", {"shop": "garden_centre"}),
        _osm(13, "Webster Lawn", {"craft": "gardener"}),
        # dentist: 5
        _osm(14, "Smile Dental", {"amenity": "dentist"}),
        _osm(15, "East Ave Dentistry", {"healthcare": "dentist"}),
        _osm(16, "Park Ave Dental", {"amenity": "dentist"}),
        _osm(17, "Henrietta Family Dental", {"amenity": "dentist"}),
        _osm(18, "Greece Dental Care", {"amenity": "dentist"}),
        # roofer: 1
        _osm(19, "Summit Roofing", {"craft": "roofer"}),
        # electrician: 5
        _osm(20, "Volt Electric", {"craft": "electrician"}),
        _osm(21, "Rochester Electric Co", {"craft": "electrician"}),
        _osm(22, "Fairport Electric", {"craft": "electrician"}),
        _osm(23, "Sparks & Sons", {"craft": "electrician"}),
        _osm(24, "Bright Power", {"craft": "electrician"}),
        # an unrelated business: must never be counted
        _osm(25, "Corner Coffee", {"amenity": "cafe"}),
        # a way with a centre coordinate and no name: skipped, never invented
        {"type": "way", "id": 90, "center": {"lat": 43.16, "lon": -77.61},
         "tags": {"shop": "hvac"}},
    ]


def _overpass_http(query: str, *a, **k):
    """A fake Overpass interpreter: answers ONE category's query at a time.

    The adapter issues one request per category, so the fake filters the full
    element list down to the elements whose tags match the QL it was handed.
    """
    wanted = []
    for line in str(query).splitlines():
        line = line.strip()
        if not line.startswith("nwr["):
            continue
        try:
            key, value = line.split("[", 1)[1].split("]", 1)[0].split("=")
        except ValueError:  # pragma: no cover - defensive
            continue
        wanted.append((key.strip('"'), value.strip('"')))
    elements = [
        e for e in _overpass_elements()
        if any(str((e.get("tags") or {}).get(key) or "") == value
               for key, value in wanted)
    ]
    return 200, json.dumps({"version": 0.6, "generator": "Overpass API",
                            "osm3s": {"timestamp_osm_base": "2026-11-18T00:00:00Z"},
                            "elements": elements})


def _open_meteo_payload():
    """Seven days: a 3-day dry run, one 92°F day, one 18°F night."""
    return {
        "latitude": 43.1566, "longitude": -77.6088,
        "timezone": "America/New_York",
        "current": {"time": "2026-11-18T12:00", "temperature_2m": 57.5,
                    "precipitation": 0.0},
        "current_units": {"temperature_2m": "°F", "precipitation": "inch"},
        "daily_units": {"temperature_2m_max": "°F", "temperature_2m_min": "°F",
                        "precipitation_sum": "inch"},
        "daily": {
            "time": ["2026-11-18", "2026-11-19", "2026-11-20", "2026-11-21",
                     "2026-11-22", "2026-11-23", "2026-11-24"],
            "temperature_2m_max": [57.5, 62.0, 60.0, 92.0, 55.0, 41.0, 38.0],
            "temperature_2m_min": [38.0, 46.0, 39.0, 61.0, 33.0, 18.0, 22.0],
            "precipitation_sum": [0.0, 0.0, 0.0, 0.62, 0.0, 0.0, 0.11],
        },
        # 48 hours of hourly precipitation: two wet hours inside the window.
        "hourly_units": {"precipitation": "inch"},
        "hourly": {
            "time": [f"2026-11-18T{h:02d}:00" for h in range(48)],
            "precipitation": [0.0] * 10 + [0.08, 0.12] + [0.0] * 36,
        },
    }


# ===========================================================================
# (a) Overpass success -> cited claims + one signal per category
# ===========================================================================
def test_overpass_success_counts_each_category_and_dedupes(monkeypatch):
    monkeypatch.setattr(overpass, "_http", _overpass_http)

    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    assert result["http_code"] == 200
    assert result["rows"], "a successful count must return real rows"

    market = result["market"]
    counts = {c["category"]: c["count"] for c in market["categories"]}

    # The dual-tagged business is counted ONCE, under HVAC (first in order).
    assert counts["HVAC contractor"] == 6
    assert counts["plumber"] == 2, "the shop=hvac business must not be double-counted"
    assert counts["landscaper"] == 5
    assert counts["dentist"] == 5
    assert counts["roofer"] == 1
    assert counts["electrician"] == 5
    # 6+2+5+5+1+5 = 24 distinct businesses; the cafe and the unnamed way are out.
    assert market["total"] == 24
    assert len(result["rows"]) == 24
    assert market["truncated"] is False

    # Rows are dicts with the documented shape, each with its own permalink.
    row = next(r for r in result["rows"] if r["name"] == "Rochester Heating & Air")
    assert set(row) == {"name", "address", "lat", "lon", "category", "source_url",
                        "mirror"}
    # The row records the interpreter that really returned its category.
    assert row["mirror"] == overpass.ENDPOINTS[0]
    assert "Main St" in row["address"]
    assert row["lat"] == pytest.approx(43.15)
    assert row["lon"] == pytest.approx(-77.60)
    assert row["category"] == "HVAC contractor"
    assert row["source_url"] == "https://www.openstreetmap.org/node/1"

    # One signal per category that has results — all six — plus the
    # addressable-market signal for businesses with no website tag.
    assert len(result["signals"]) == 7
    cats = {s["category"] for s in result["signals"] if "category" in s}
    assert cats == set(overpass.CATEGORY_LABELS)
    no_site = [s for s in result["signals"] if s["kind"] == overpass.NO_WEBSITE]
    assert len(no_site) == 1, "the no-website addressable-market signal must fire"
    assert no_site[0]["count"] == 24, "no fixture business carries a website tag"
    assert "publish no website tag" in no_site[0]["line"]
    assert no_site[0]["source_url"] == overpass.ENDPOINTS[0]
    for sig in result["signals"]:
        assert sig["source_url"] == overpass.ENDPOINTS[0], "cite the mirror that served it"
        assert "within 50 miles of Rochester, NY" in sig["line"]
    hvac = next(s for s in result["signals"] if s["category"] == "HVAC contractor")
    assert "6 HVAC contractors within 50 miles of Rochester, NY" in hvac["line"]


def test_overpass_success_writes_cited_claims(monkeypatch):
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    _probe_only("overpass")

    before = _claim_count()
    summary = _ingest(["overpass"])

    entry = summary["overpass"]
    assert entry["status"] == "OK"
    assert entry["signals"] == 7
    assert entry["claims_written"] >= 1
    assert _claim_count() == before + entry["claims_written"]

    # HARD RULE: no claim exists without BOTH a source_url and a source_turn.
    claims = _all_claims()
    assert claims
    for claim in claims:
        assert str(claim.get("source_url") or "").strip(), "uncited claim written"
        assert str(claim.get("source_turn") or "").strip(), "uncited claim written"
        assert claim["source_url"] == overpass.ENDPOINTS[0], "the real mirror, not a guess"
        assert claim["source_turn"].startswith("live_data:overpass@")


def test_overpass_full_page_is_labelled_at_least(monkeypatch):
    """A category response that fills the page limit is a floor, not a total."""
    monkeypatch.setattr(overpass, "_http", _overpass_http)

    # HVAC has 6 elements, so a page size of 6 fills it exactly.
    result = overpass.snapshot(limit=6)
    assert result["status"] == overpass.OK
    assert result["market"]["truncated"] is True
    hvac = next(c for c in result["market"]["categories"]
                if c["category"] == "HVAC contractor")
    assert hvac["capped"] is True
    sig = next(s for s in result["signals"] if s["category"] == "HVAC contractor")
    assert "at least 6 HVAC contractors" in sig["line"]
    assert "page limit" in result["reason"]


# ===========================================================================
# (b) Overpass failure -> ZERO claims, honest status, literal reason
# ===========================================================================
def test_overpass_429_writes_zero_claims_and_reports_rate_limited(monkeypatch):
    literal = "HTTP 429: Too Many Requests — please wait a moment"
    monkeypatch.setattr(overpass, "_http", lambda *a, **k: (429, literal))
    monkeypatch.setattr(overpass, "MAX_ATTEMPTS", 1)

    assert overpass.classify(429) == overpass.RATE_LIMITED
    assert overpass.classify(504) == overpass.TIMEOUT
    assert overpass.classify(500) == overpass.DEGRADED
    assert overpass.classify(200) == overpass.OK

    result = overpass.snapshot()
    assert result["status"] == overpass.RATE_LIMITED
    assert result["http_code"] == 429
    assert literal in result["reason"], "the literal reason must be kept verbatim"
    assert result["rows"] == []
    assert result["places"] == []
    assert result["signals"] == []
    assert all(c["count"] is None for c in result["market"]["categories"]), \
        "an unmeasured category is None, never 0"

    _probe_only("overpass")
    before = _claim_count()
    summary = _ingest(["overpass"])

    entry = summary["overpass"]
    assert entry["status"] == "DEGRADED"
    assert entry["signals"] == 0
    assert entry["claims_written"] == 0
    assert literal in entry["reason"]
    assert _claim_count() == before, "a failed source must write NOTHING"


def test_overpass_504_reports_timeout(monkeypatch):
    monkeypatch.setattr(overpass, "_http", lambda *a, **k: (504, "Gateway Timeout"))
    monkeypatch.setattr(overpass, "MAX_ATTEMPTS", 1)

    result = overpass.snapshot()
    assert result["status"] == overpass.TIMEOUT
    assert "HTTP 504" in result["reason"]
    assert result["rows"] == []
    assert result["signals"] == []


def test_overpass_unparseable_body_is_degraded_with_zero_claims(monkeypatch):
    monkeypatch.setattr(overpass, "_http", lambda *a, **k: (200, "<html>not json</html>"))
    result = overpass.snapshot()
    assert result["status"] == overpass.DEGRADED
    assert "did not parse" in result["reason"]
    assert result["rows"] == []
    assert result["signals"] == []


def test_overpass_partial_failure_keeps_the_categories_that_answered(monkeypatch):
    """One throttled category must not erase the five that answered."""
    def flaky(query, *a, **k):
        if '"craft"="plumber"' in query:
            return 429, "HTTP 429: Too Many Requests"
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", flaky)
    monkeypatch.setattr(overpass, "MAX_ATTEMPTS", 1)

    # Resilient mode: one request per category, so one throttle is survivable.
    result = overpass.snapshot(per_category=True)
    assert result["status"] == overpass.OK
    counts = {c["category"]: c for c in result["market"]["categories"]}
    assert counts["plumber"]["count"] is None, "a throttled category is not measured"
    assert counts["plumber"]["status"] == overpass.RATE_LIMITED
    assert counts["HVAC contractor"]["count"] == 6
    # No signal for the category that never answered.
    assert "plumber" not in {s.get("category") for s in result["signals"]}


# ===========================================================================
# (c) Open-Meteo success -> cited claims
# ===========================================================================
def test_open_meteo_success_emits_cited_signals(monkeypatch):
    monkeypatch.setattr(open_meteo, "_http",
                        lambda *a, **k: (200, json.dumps(_open_meteo_payload())))

    result = open_meteo.snapshot()
    assert result["status"] == open_meteo.OK
    assert result["http_code"] == 200
    assert len(result["rows"]) == 7

    kinds = {s["kind"] for s in result["signals"]}
    assert open_meteo.DEMAND_DIP in kinds, "3 dry days in a row is a demand dip"
    assert open_meteo.HEAT_SPIKE in kinds, "a 92°F forecast high is a heat spike"
    assert open_meteo.COLD_SNAP in kinds, "an 18°F forecast low is a cold snap"
    assert open_meteo.HEAVY_PRECIP in kinds, "0.62 in clears the 0.5 in heavy-rain threshold"

    heavy = [s for s in result["signals"] if s["kind"] == open_meteo.HEAVY_PRECIP]
    assert any("0.62 in of precipitation forecast on 2026-11-21" in s["line"]
               for s in heavy), "the heavy day must be named with its real total"
    assert any("next 48 hours" in s["line"] for s in heavy), \
        "the 48-hour hourly window must produce its own signal"

    # The 48h hourly window was actually requested and parsed.
    assert "hourly=precipitation" in result["source_url"]
    assert len(result["daily"]["hourly"]["time"]) == 48

    dip = next(s for s in result["signals"] if s["kind"] == open_meteo.DEMAND_DIP)
    assert "3 consecutive days of zero precipitation forecast for Rochester, NY" in dip["line"]

    # Every signal cites the exact Open-Meteo request URL.
    for sig in result["signals"]:
        assert sig["source_url"].startswith("https://api.open-meteo.com/v1/forecast?")
        assert "latitude=43.1566" in sig["source_url"]
    assert result["source_url"] == result["signals"][0]["source_url"]


def test_open_meteo_success_writes_cited_claims(monkeypatch):
    monkeypatch.setattr(open_meteo, "_http",
                        lambda *a, **k: (200, json.dumps(_open_meteo_payload())))
    _probe_only("open_meteo")

    before = _claim_count()
    summary = _ingest(["open_meteo"])

    entry = summary["open_meteo"]
    assert entry["status"] == "OK"
    assert entry["signals"] >= 1
    assert entry["claims_written"] >= 1
    assert _claim_count() == before + entry["claims_written"]

    claims = _all_claims()
    assert claims
    for claim in claims:
        assert str(claim.get("source_url") or "").strip(), "uncited claim written"
        assert str(claim.get("source_turn") or "").strip(), "uncited claim written"
        assert claim["source_url"].startswith("https://api.open-meteo.com/v1/forecast?")
        assert claim["source_turn"].startswith("live_data:open_meteo@")


# ===========================================================================
# (d) Open-Meteo failure -> zero claims, DEGRADED
# ===========================================================================
def test_open_meteo_http_error_writes_zero_claims_and_reports_degraded(monkeypatch):
    literal = "HTTP 503: Service Unavailable"
    monkeypatch.setattr(open_meteo, "_http", lambda *a, **k: (503, literal))

    result = open_meteo.snapshot()
    assert result["status"] == open_meteo.DEGRADED
    assert result["http_code"] == 503
    assert literal in result["reason"]
    assert result["rows"] == []
    assert result["signals"] == []

    _probe_only("open_meteo")
    before = _claim_count()
    summary = _ingest(["open_meteo"])

    entry = summary["open_meteo"]
    assert entry["status"] == "DEGRADED"
    assert entry["signals"] == 0
    assert entry["claims_written"] == 0
    assert literal in entry["reason"]
    assert _claim_count() == before, "a failed source must write NOTHING"


def test_open_meteo_unparseable_body_is_degraded(monkeypatch):
    monkeypatch.setattr(open_meteo, "_http", lambda *a, **k: (200, '{"nope": 1}'))
    result = open_meteo.snapshot()
    assert result["status"] == open_meteo.DEGRADED
    assert "did not parse" in result["reason"]
    assert result["rows"] == []
    assert result["signals"] == []


# ===========================================================================
# (e) Neither adapter ever raises on a network failure
# ===========================================================================
def test_both_adapters_never_raise_on_network_failure(monkeypatch):
    def boom(*a, **k):
        raise urllib.error.URLError("no route to host")

    monkeypatch.setattr(overpass, "_http", boom)
    monkeypatch.setattr(overpass, "MAX_ATTEMPTS", 1)
    monkeypatch.setattr(open_meteo, "_http", boom)

    op = overpass.snapshot()
    assert op["status"] == overpass.DEGRADED
    assert "URLError" in op["reason"]
    assert op["rows"] == [] and op["signals"] == []

    om = open_meteo.snapshot()
    assert om["status"] == open_meteo.DEGRADED
    assert "URLError" in om["reason"]
    assert om["rows"] == [] and om["signals"] == []

    # And through the bridge: still zero claims, still no crash.
    _probe_only("overpass")
    _probe_only("open_meteo")
    before = _claim_count()
    summary = _ingest(["overpass", "open_meteo"])
    for sid in ("overpass", "open_meteo"):
        assert summary[sid]["status"] == "DEGRADED"
        assert summary[sid]["claims_written"] == 0
    assert _claim_count() == before


# ===========================================================================
# wiring: both adapters are registered, keyless, and scoped
# ===========================================================================
def test_both_keyless_sources_are_registered_with_no_credential():
    ids = {s["id"]: s for s in live_data.SOURCES}
    assert "overpass" in ids and "open_meteo" in ids
    for sid in ("overpass", "open_meteo"):
        assert ids[sid]["keyless"] is True
        assert ids[sid]["credential_env"] == "", "a keyless source declares no credential"
    # The existing keyed adapters are still there, untouched.
    for sid in ("mapbox", "xweather", "massive"):
        assert sid in ids

    assert "overpass" in live_ingest.BRIDGED_SOURCE_IDS
    assert "open_meteo" in live_ingest.BRIDGED_SOURCE_IDS


def test_overpass_scope_line_is_the_countable_market_line():
    line = overpass.scope_line()
    assert line == "Countable market — Rochester, NY · 50-mile radius"
    card = next(c for c in live_data.cards() if c["id"] == "overpass")
    assert card["scope"] == line
    assert card["keyless"] is True


def test_live_data_page_serves_both_new_rows_and_the_scope_line(monkeypatch):
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    monkeypatch.setattr(open_meteo, "_http",
                        lambda *a, **k: (200, json.dumps(_open_meteo_payload())))
    _probe_only("overpass")
    _probe_only("open_meteo")

    from app import create_app

    client = create_app().test_client()
    html = client.get("/live-data").get_data(as_text=True)

    assert 'data-source="overpass"' in html
    assert 'data-source="open_meteo"' in html
    assert "Countable market — Rochester, NY · 50-mile radius" in html
    assert "keyless" in html
    # The real per-category counts are rendered, not a placeholder.
    assert 'data-mkt-category="HVAC contractor" data-mkt-count="6"' in html
    assert 'data-mkt-category="dentist" data-mkt-count="5"' in html


def test_live_data_page_renders_unmeasured_categories_when_degraded(monkeypatch):
    """A DEGRADED capture still renders the tiles: "—" / not measured, never 0.

    The per-category counts are structurally ``None`` on a failure, so the page
    must show every category as unmeasured with its literal reason in the tile
    tooltip — not hide the grid, and not print a zero that reads as "found none".
    """
    literal = "server is currently at capacity / request queue is full"
    overpass.reset_cache()
    monkeypatch.setattr(overpass, "_http", lambda *a, **k: (502, literal))
    entry = _probe_only("overpass")
    assert entry["status"] == "DEGRADED"
    assert all(c["count"] is None for c in entry["market"]["categories"])

    from app import create_app

    html = create_app().test_client().get("/live-data").get_data(as_text=True)

    # The scope line and the row are still on the page.
    assert "Countable market — Rochester, NY · 50-mile radius" in html
    assert 'data-source="overpass"' in html
    # Every category is rendered as UNMEASURED, with no fabricated count.
    measured_flags = re.findall(r'data-mkt-measured="([^"]+)"', html)
    assert measured_flags and set(measured_flags) == {"false"}
    assert re.search(r'data-mkt-category="HVAC contractor" data-mkt-count=""', html)
    assert html.count('class="mkcount unk">&mdash;') >= len(overpass.CATEGORIES)
    assert "not measured" in html
    # The literal reason is the tile tooltip, verbatim from the endpoint.
    assert 'title="HTTP 502: ' in html
    assert literal in html
    assert "data-mkt-capped" in html


def test_live_data_page_renders_the_overpass_transport_line(monkeypatch):
    """The card states the transport, and names the mirror that really served it.

    Regression: the block existed but the rendered page had no transport div at
    all, because the running process was serving an older adapter whose
    ``market`` block carried no ``transport`` / ``served_by`` fields. The line
    must render from the adapter's own provenance, never from a template guess.
    """
    overpass.reset_cache()
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    entry = _probe_only("overpass")
    assert entry["status"] == "LIVE"
    assert entry["market"]["transport"] == overpass.transport_note()
    assert "4-mirror failover" in entry["market"]["transport"]

    from app import create_app

    html = create_app().test_client().get("/live-data").get_data(as_text=True)

    assert 'id="overpassTransport"' in html
    assert overpass.transport_note() in html
    # The mirror that actually answered is named — and it is the real host.
    assert 'data-served-by="maps.mail.ru"' in html
    assert "served by <b>maps.mail.ru</b>" in html
    assert 'data-mirror-count="4"' in html
    assert f'data-cache-ttl="{overpass.CACHE_TTL_SECONDS}"' in html
    # Nothing came from the cache on a cold run, so the page must not say so.
    assert 'data-cached="false"' in html
    assert "category count(s) from the" not in html


def test_live_data_page_says_cache_hit_when_the_count_came_from_cache(monkeypatch):
    """A repeat run is served from the disk cache, and the card says so."""
    overpass.reset_cache()
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    _probe_only("overpass")
    entry = _probe_only("overpass")  # second run: every category is a cache hit
    assert entry["market"]["cached_any"] is True

    from app import create_app

    html = create_app().test_client().get("/live-data").get_data(as_text=True)
    assert 'data-cached="true"' in html
    assert (f"{len(overpass.CATEGORIES)} of {len(overpass.CATEGORIES)} category "
            f"count(s) from the {overpass.CACHE_TTL_SECONDS // 3600}-hour cache") in html


def test_live_data_page_transport_line_is_honest_when_nothing_was_recorded(monkeypatch):
    """No recorded mirror -> no mirror claimed. The line still renders.

    A capture with no provenance (an older capture, or a run where every mirror
    failed) must not be dressed up as "served by" anything: the fallback states
    that the transport was not recorded, and the DEGRADED card says no mirror
    served it.
    """
    literal = "server is currently at capacity / request queue is full"
    overpass.reset_cache()
    monkeypatch.setattr(overpass, "_http", lambda *a, **k: (502, literal))
    entry = _probe_only("overpass")
    assert entry["status"] == "DEGRADED"
    assert entry["market"]["served_by"] == "", "a failed run must not name a mirror"
    assert all(c["count"] is None for c in entry["market"]["categories"])

    from app import create_app

    html = create_app().test_client().get("/live-data").get_data(as_text=True)
    assert 'id="overpassTransport"' in html
    assert 'data-served-by=""' in html
    assert "served by <b>" not in html
    # Every mirror was tried and refused: the card states the attempts, verbatim.
    assert "mirror attempt(s) failed" in html
    # One failed attempt per mirror per category — counted, not guessed.
    assert (f'data-mirrors-attempted="{len(entry["market"]["mirror_failures"])}"'
            in html)
    assert len(entry["market"]["mirror_failures"]) >= len(overpass.ENDPOINTS)
    # The transport note is still stated: it describes what was attempted.
    assert overpass.transport_note() in html
    # And the failure is a clean gap: zero rows, zero claims, no zero counts.
    assert entry["rows"] == []
    assert re.search(r'data-mkt-category="HVAC contractor" data-mkt-count=""', html)


def test_live_data_page_transport_falls_back_when_the_market_has_no_provenance(monkeypatch):
    """An older capture (no transport fields) renders a stated fallback, not a blank."""
    overpass.reset_cache()
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    _probe_only("overpass")

    # Simulate a capture recorded before the provenance fields existed: the
    # market block is there, the transport keys are not.
    entry = live_data._LATEST["overpass"]
    for key in ("transport", "served_by", "mirror_count", "cache_ttl_seconds",
                "cached_any", "cached_categories"):
        entry["market"].pop(key, None)

    from app import create_app

    html = create_app().test_client().get("/live-data").get_data(as_text=True)
    assert 'id="overpassTransport"' in html
    assert "transport not recorded for this capture" in html
    assert "served by <b>" not in html
    # The counts themselves are untouched: only the provenance line degrades.
    assert 'data-mkt-category="HVAC contractor" data-mkt-count="6"' in html


def test_ingest_endpoint_reports_both_keyless_sources(monkeypatch):
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    monkeypatch.setattr(open_meteo, "_http",
                        lambda *a, **k: (200, json.dumps(_open_meteo_payload())))
    _probe_only("overpass")
    _probe_only("open_meteo")

    from app import create_app

    client = create_app().test_client()
    resp = client.post("/live-data/ingest")
    assert resp.status_code == 200
    body = resp.get_json()

    for sid in ("overpass", "open_meteo"):
        assert sid in body, f"{sid} missing from the per-source breakdown"
        assert body[sid]["status"] == "OK"
        assert body[sid]["signals"] >= 1
        assert body[sid]["claims_written"] >= 1
    # The keyed adapters are still reported, honestly.
    assert body["mapbox"]["status"] == "DEGRADED"
    assert body["mapbox"]["claims_written"] == 0


# ===========================================================================
# (f) the single-query shape the spec asks for
# ===========================================================================
def test_overpass_issues_one_small_query_per_category(monkeypatch):
    """The default path is SIX small requests, one category each — not one union.

    The single six-category union query is what the loaded public endpoint 502s
    on ("server is currently at capacity / request queue is full"), so each
    category gets its own cheap request.
    """
    overpass.reset_cache()
    calls = []

    def counting(query, *a, **k):
        calls.append(query)
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", counting)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    assert len(calls) == len(overpass.CATEGORIES), \
        f"expected one query per category, got {len(calls)}"
    # Each request carries ONLY its own category's tag filters.
    for query in calls:
        assert query.startswith("[out:json][timeout:25];")
        assert "out center" in query
        assert "(around:80467,43.156600,-77.608800)" in query, "same centre + radius"
        assert query.count("nwr[") <= 2, "a per-category query is small"
    joined = "\n".join(calls)
    for _label, tags in overpass.CATEGORIES:
        for key, value in tags:
            assert f'nwr["{key}"="{value}"]' in joined, f"{key}={value} missing"
    # And the counts are still right, de-duplicated across categories.
    counts = {c["category"]: c["count"] for c in result["market"]["categories"]}
    assert counts["HVAC contractor"] == 6
    assert counts["plumber"] == 2, "the dual-tagged business is counted once, under HVAC"
    assert counts["dentist"] == 5
    assert counts["roofer"] == 1


# ===========================================================================
# (f2) MIRROR FAILOVER — 502 on the first mirror, the second one serves
# ===========================================================================
def test_overpass_mirror_failover_502_then_second_mirror_serves(monkeypatch):
    """A saturated main instance costs one short hop, not the whole run."""
    overpass.reset_cache()
    tried = []

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        if endpoint == overpass.ENDPOINTS[0]:
            return 502, "server is currently at capacity / request queue is full"
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    # The mirror that actually served the response is recorded, not guessed.
    assert result["mirror"] == overpass.ENDPOINTS[1]
    assert result["source_url"] == overpass.ENDPOINTS[1]
    assert result["market"]["mirror"] == overpass.ENDPOINTS[1]
    for cat in result["market"]["categories"]:
        assert cat["mirror"] == overpass.ENDPOINTS[1], "per-category provenance"
        assert cat["measured"] is True
    # The first mirror was tried, its literal reason kept, and — because a 502 is
    # a property of the instance right now, not of the query — it is then put on a
    # short cooldown instead of being re-tried for all six categories.
    assert tried.count(overpass.ENDPOINTS[0]) >= 1
    assert tried.count(overpass.ENDPOINTS[0]) < len(overpass.CATEGORIES), \
        "a mirror that just 502'd is cooled down, not re-tried six times"
    assert result["mirror_failures"], "the 502 must be recorded, not swallowed"
    assert "capacity" in result["mirror_failures"][0]["reason"]
    assert result["mirror_failures"][0]["http_code"] == 502
    # Real counts still came through.
    counts = {c["category"]: c["count"] for c in result["market"]["categories"]}
    assert counts["HVAC contractor"] == 6
    assert counts["plumber"] == 2


def test_overpass_mirror_failover_on_timeout(monkeypatch):
    """A hung mirror is abandoned after the short ceiling; the next one answers."""
    overpass.reset_cache()
    tried = []

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        if endpoint == overpass.ENDPOINTS[0]:
            raise TimeoutError("timed out")
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    assert result["mirror"] == overpass.ENDPOINTS[1]
    assert "TimeoutError" in result["mirror_failures"][0]["reason"]
    # Short and bounded: a hung mirror costs at most this much before the next
    # one is tried (measured healthy serve on this box: 13.9s).
    assert 20 <= overpass.MIRROR_TIMEOUT_SECONDS <= 25, "a short per-request ceiling"


def test_overpass_mirror_failover_walks_the_whole_list(monkeypatch):
    """502 on the first two mirrors, the third one serves."""
    overpass.reset_cache()

    def fake(query, endpoint=None, *a, **k):
        if endpoint in overpass.ENDPOINTS[:2]:
            return 503, "Service Unavailable"
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    assert result["mirror"] == overpass.ENDPOINTS[2]
    # Both dead mirrors are recorded — once each, then cooled down rather than
    # re-tried for every remaining category.
    assert len(result["mirror_failures"]) >= 2
    assert {f["endpoint"] for f in result["mirror_failures"]} == set(overpass.ENDPOINTS[:2])


# ===========================================================================
# (f3) ALL MIRRORS FAIL -> DEGRADED, zero claims, nothing fabricated
# ===========================================================================
def test_overpass_all_mirrors_fail_reports_degraded_and_writes_zero_claims(monkeypatch):
    overpass.reset_cache()
    tried = []
    literal = "server is currently at capacity / request queue is full"

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        return 502, literal

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.DEGRADED
    assert literal in result["reason"], "the literal reason must be kept verbatim"
    assert result["rows"] == []
    assert result["places"] == []
    assert result["signals"] == []
    assert result["count"] == 0
    assert all(c["count"] is None for c in result["market"]["categories"]), \
        "an unmeasured category is None, never 0"
    assert all(c["measured"] is False for c in result["market"]["categories"])
    # Every mirror in the list was actually tried.
    assert set(tried) == set(overpass.ENDPOINTS)

    # And through the bridge: zero claims, no crash.
    _probe_only("overpass")
    before = _claim_count()
    summary = _ingest(["overpass"])
    entry = summary["overpass"]
    assert entry["status"] == "DEGRADED"
    assert entry["signals"] == 0
    assert entry["claims_written"] == 0
    assert literal in entry["reason"]
    assert _claim_count() == before, "a failed source must write NOTHING"


# ===========================================================================
# (f4) CACHING — a repeat run is cheap; the key is category + centre + radius
# ===========================================================================
def test_overpass_caches_successful_categories(monkeypatch):
    overpass.reset_cache()
    calls = []

    def counting(query, *a, **k):
        calls.append(query)
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", counting)
    first = overpass.snapshot()
    assert first["status"] == overpass.OK
    assert len(calls) == len(overpass.CATEGORIES)

    second = overpass.snapshot()
    assert len(calls) == len(overpass.CATEGORIES), "a repeat run must hit the cache"
    assert second["status"] == overpass.OK
    assert all(c["cached"] for c in second["market"]["categories"])
    counts = {c["category"]: c["count"] for c in second["market"]["categories"]}
    assert counts["HVAC contractor"] == 6, "cached counts are the real counts"

    # A different radius is a different cache key -> a real refetch.
    overpass.snapshot(radius_miles=25)
    assert len(calls) == 2 * len(overpass.CATEGORIES)


def test_overpass_failures_are_never_cached(monkeypatch):
    """A category that failed is retried, never remembered as a failure or a zero."""
    overpass.reset_cache()
    state = {"fail": True}

    def flaky(query, *a, **k):
        if state["fail"] and '"craft"="roofer"' in query:
            return 502, "server is currently at capacity"
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", flaky)
    first = overpass.snapshot()
    counts = {c["category"]: c for c in first["market"]["categories"]}
    assert counts["roofer"]["count"] is None
    assert first["market"]["partial"] is True

    state["fail"] = False
    second = overpass.snapshot()
    counts = {c["category"]: c for c in second["market"]["categories"]}
    assert counts["roofer"]["count"] == 1, "the failed category was retried, not cached"
    assert counts["roofer"]["cached"] is False
    assert counts["HVAC contractor"]["cached"] is True, "the successes stayed cached"


# ===========================================================================
# (f5) THE FOUR MIRRORS, THE 15-MINUTE CACHE AND THE TRANSPORT PROVENANCE
# ===========================================================================
def test_overpass_mirror_list_is_the_four_documented_endpoints():
    """The failover list is exactly the four interpreters, mirror-first.

    Measured on this box: the canonical instance queued every one-category query
    past 30s while maps.mail.ru answered in 13.9s, so the canonical instance is
    tried LAST. It is still the citation of record when nothing answered.
    """
    assert overpass.ENDPOINTS == (
        "https://maps.mail.ru/osm/tools/overpass/api/interpreter",
        "https://overpass.kumi.systems/api/interpreter",
        "https://overpass.private.coffee/api/interpreter",
        "https://overpass-api.de/api/interpreter",
    )
    assert set(overpass.ENDPOINTS) == {
        "https://overpass-api.de/api/interpreter",
        "https://overpass.kumi.systems/api/interpreter",
        "https://overpass.private.coffee/api/interpreter",
        "https://maps.mail.ru/osm/tools/overpass/api/interpreter",
    }
    assert overpass.SOURCE_URL == "https://overpass-api.de/api/interpreter"
    assert overpass.ENDPOINT == overpass.SOURCE_URL


def test_overpass_cache_ttl_is_six_hours_and_on_disk():
    """A repeat ingest is free, and the cache survives a restart."""
    assert overpass.CACHE_TTL_SECONDS == 6 * 60 * 60
    assert overpass.cache_stats()["ttl_seconds"] == 21600
    assert overpass.CACHE_DIR.endswith("overpass_cache")
    note = overpass.transport_note()
    assert "4-mirror failover" in note
    assert "6-hour disk cache" in note


def test_overpass_result_exposes_transport_and_cache_provenance(monkeypatch):
    """Which mirror served it, and whether the count came from the cache."""
    overpass.reset_cache()
    monkeypatch.setattr(overpass, "_http", _overpass_http)

    first = overpass.snapshot()
    assert first["status"] == overpass.OK
    assert first["served_by"] == "maps.mail.ru"
    assert first["transport"] == overpass.transport_note()
    assert first["cached_any"] is False
    assert first["cache_ttl_seconds"] == 21600

    second = overpass.snapshot()
    assert second["cached_any"] is True, "a repeat run must say it came from cache"
    assert len(second["market"]["cached_categories"]) == len(overpass.CATEGORIES)
    assert second["market"]["transport"] == first["transport"]


def test_overpass_expired_cache_is_refetched(monkeypatch):
    """Past the TTL the entry is dropped: a stale count is never served."""
    overpass.reset_cache()
    calls = []

    def counting(query, *a, **k):
        calls.append(query)
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", counting)
    overpass.snapshot()
    assert len(calls) == len(overpass.CATEGORIES)

    for entry in overpass._CACHE.values():
        entry["stored_at"] -= overpass.CACHE_TTL_SECONDS + 1

    overpass.snapshot()
    assert len(calls) == 2 * len(overpass.CATEGORIES), "an expired entry is refetched"


def test_overpass_fetch_never_starts_a_request_past_the_budget(monkeypatch):
    """A hung run must not spend its last seconds starting another mirror hop."""
    tried = []

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        return 502, "server is currently at capacity"

    monkeypatch.setattr(overpass, "_http", fake)
    ql = overpass.build_category_query("plumber", (("craft", "plumber"),))
    code, text, endpoint, failures = overpass._fetch(ql, deadline=time.monotonic() - 5)
    assert tried == [], "no request may be started with the budget gone"
    assert code == 0
    assert endpoint == ""
    assert "budget" in text


def test_overpass_union_query_is_the_documented_shape():
    ql = overpass.union_query()
    assert ql.startswith("[out:json][timeout:25];")
    assert ql.count("nwr[") == 9, "6 categories over 9 tag pairs"
    assert ql.rstrip().endswith("out center 1200;")


# ===========================================================================
# (h) HARDENING — mirror fallback, partial failure, disk cache, total failure
# ===========================================================================
def test_overpass_hardening_mirror_fallback_on_502(monkeypatch):
    """(a) A 502 from the first mirror is failed over; the next one serves.

    The claim source URL must be the mirror that REALLY answered, not the first
    endpoint in the list and not a hardcoded one.
    """
    overpass.reset_cache()
    tried = []

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        if endpoint == overpass.ENDPOINTS[0]:
            return 502, "server is currently at capacity / request queue is full"
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    assert tried[0] == overpass.ENDPOINTS[0], "the list is tried in order"
    assert result["mirror"] == overpass.ENDPOINTS[1]
    assert result["source_url"] == overpass.ENDPOINTS[1]
    assert result["market"]["served_by"] == "overpass.kumi.systems"
    # The 502 is recorded verbatim, with the code, against the mirror that gave it.
    first = result["mirror_failures"][0]
    assert first["endpoint"] == overpass.ENDPOINTS[0]
    assert first["http_code"] == 502
    assert "capacity" in first["reason"]
    # Every category carries the mirror that served it, and every signal cites it.
    for cat in result["market"]["categories"]:
        assert cat["mirror"] == overpass.ENDPOINTS[1]
        assert cat["cached"] is False
    for sig in result["signals"]:
        assert sig["source_url"] == overpass.ENDPOINTS[1]
    # Real counts still came through, and the row names its serving mirror.
    counts = {c["category"]: c["count"] for c in result["market"]["categories"]}
    assert counts["HVAC contractor"] == 6 and counts["plumber"] == 2
    assert {r["mirror"] for r in result["rows"]} == {overpass.ENDPOINTS[1]}


def test_overpass_hardening_partial_failure_keeps_the_others(monkeypatch):
    """(b) One category fails on every mirror; the other five still report.

    The failed category is ``count: None`` with its literal reason — never 0 —
    and the source stays OK because five of six categories were measured.
    """
    overpass.reset_cache()

    def fake(query, endpoint=None, *a, **k):
        if 'nwr["amenity"="dentist"]' in query or 'nwr["healthcare"="dentist"]' in query:
            return 504, "Gateway Timeout"
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK, "one slow category must not kill the run"
    market = result["market"]
    counts = {c["category"]: c["count"] for c in market["categories"]}
    assert counts["dentist"] is None, "an unmeasured category is None, never 0"
    assert counts["HVAC contractor"] == 6
    assert counts["plumber"] == 2
    assert counts["landscaper"] == 5
    assert counts["roofer"] == 1
    assert counts["electrician"] == 5
    assert market["partial"] is True
    assert market["failed_categories"] == ["dentist"]
    assert market["measured_categories"] == 5
    dentist = next(c for c in market["categories"] if c["category"] == "dentist")
    assert dentist["measured"] is False
    assert "504" in dentist["reason"] and "Gateway Timeout" in dentist["reason"]
    # No signal is emitted for the unmeasured category, and no claim can be.
    assert not [s for s in result["signals"] if s.get("category") == "dentist"]
    assert all(c["count"] != 0 for c in market["categories"]), "never a fabricated zero"
    # The dentist failure is recorded against every mirror that refused it.
    assert {f["endpoint"] for f in result["mirror_failures"]} == set(overpass.ENDPOINTS)


def test_overpass_hardening_cache_hit_is_marked_cached(monkeypatch):
    """(c) A second run inside the TTL is served from disk and says so."""
    overpass.reset_cache()
    calls = []

    def counting(query, *a, **k):
        calls.append(query)
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", counting)
    first = overpass.snapshot()
    assert first["status"] == overpass.OK
    assert len(calls) == len(overpass.CATEGORIES), "one query per category"
    assert first["cached_any"] is False

    # The cache is on disk, so it survives a process restart: drop the in-memory
    # map and prove the second run is still served without touching the network.
    with overpass._CACHE_LOCK:
        overpass._CACHE.clear()
        overpass._LOADED = False

    second = overpass.snapshot()
    assert len(calls) == len(overpass.CATEGORIES), "a cache hit must not re-query"
    assert second["status"] == overpass.OK
    assert second["cached_any"] is True
    assert len(second["market"]["cached_categories"]) == len(overpass.CATEGORIES)
    for cat in second["market"]["categories"]:
        assert cat["cached"] is True
        assert cat["count"] is not None, "a cached count is a real count"
        assert cat["cache_age_seconds"] >= 0
    # The counts are identical to the live run — the cache never invents a number.
    assert ({c["category"]: c["count"] for c in second["market"]["categories"]}
            == {c["category"]: c["count"] for c in first["market"]["categories"]})
    # And the mirror that really served the cached bytes is still recorded.
    assert second["market"]["served_by"] == "maps.mail.ru"


def test_overpass_hardening_total_failure_writes_zero_claims(monkeypatch):
    """(d) Every mirror down -> DEGRADED, literal reason, zero claims written."""
    overpass.reset_cache()
    literal = "server is currently at capacity / request queue is full"
    monkeypatch.setattr(overpass, "_http", lambda *a, **k: (502, literal))

    before = _claim_count()
    entry = _probe_only("overpass")
    assert entry["status"] == "DEGRADED"
    assert literal in entry["detail"], "the upstream reason is kept verbatim"
    assert entry["rows"] == []
    assert all(c["count"] is None for c in entry["market"]["categories"])
    assert entry["market"]["total"] == 0
    assert entry["market"]["served_by"] == "", "no mirror may be named"
    # Every mirror was tried, and the reason says so.
    assert len(entry["market"]["mirror_failures"]) >= len(overpass.ENDPOINTS)
    assert "all 4 mirror(s) failed" in entry["detail"]
    assert "0 of 6 categories measured, 0 claims written" in entry["detail"]

    summary = _ingest(["overpass"])
    assert summary["overpass"]["status"] == "DEGRADED"
    assert summary["overpass"]["claims_written"] == 0
    assert summary["overpass"]["signals"] == 0
    assert _claim_count() == before, "a total failure must write ZERO claims"


# ===========================================================================
# (g) idempotency — running ingest twice must not duplicate claims
# ===========================================================================
def test_ingest_twice_does_not_duplicate_claims(monkeypatch):
    monkeypatch.setattr(overpass, "_http", _overpass_http)
    monkeypatch.setattr(open_meteo, "_http",
                        lambda *a, **k: (200, json.dumps(_open_meteo_payload())))
    _probe_only("overpass")
    _probe_only("open_meteo")

    first = _ingest(["overpass", "open_meteo"])
    after_first = _claim_count()
    assert first["overpass"]["claims_written"] >= 1
    assert first["open_meteo"]["claims_written"] >= 1

    second = _ingest(["overpass", "open_meteo"])
    after_second = _claim_count()

    assert after_second == after_first, "a re-run must not write duplicate claims"
    for sid in ("overpass", "open_meteo"):
        assert second[sid]["claims_written"] == 0, "nothing new to write the second time"
        assert second[sid]["claims_skipped"] >= 1, "the existing claims were skipped"
        assert second[sid]["status"] == "OK"

    # No claim text+turn pair appears twice.
    pairs = [(c["text"], c["source_turn"]) for c in _all_claims()]
    assert len(pairs) == len(set(pairs)), "duplicate claim rows found"


# ===========================================================================
# (f4) MIRROR COOLDOWN — a dead mirror is paid for once, not six times
# ===========================================================================
def test_overpass_dead_mirror_is_cooled_down_not_retried_per_category(monkeypatch):
    """Two hanging mirrors must not cost 2 x ceiling x 6 categories.

    Measured on this box: kumi.systems and private.coffee did not answer inside
    70s while overpass-api.de answered in ~41s. Without a cooldown that is two
    full ceilings paid on EVERY category; with it, the first category pays and
    the rest go straight to the mirror that answers.
    """
    overpass.reset_cache()
    tried = []

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        if endpoint in overpass.ENDPOINTS[:2]:
            raise TimeoutError("The read operation timed out")
        return _overpass_http(query)

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.OK
    assert result["mirror"] == overpass.ENDPOINTS[2]
    # The two dead mirrors were each attempted once, not once per category.
    assert tried.count(overpass.ENDPOINTS[0]) == 1
    assert tried.count(overpass.ENDPOINTS[1]) == 1
    # The healthy mirror served every category.
    assert tried.count(overpass.ENDPOINTS[2]) == len(overpass.CATEGORIES)
    # The two that hung are cooling; the one that answered is not.
    cooling = set(overpass.cooldown_state())
    assert cooling == set(overpass.ENDPOINTS[:2])
    assert overpass.ENDPOINTS[2] not in cooling


def test_overpass_cooldown_never_empties_the_mirror_list(monkeypatch):
    """If every mirror is cooling, the whole list is tried again — never skipped."""
    overpass.reset_cache()
    for endpoint in overpass.ENDPOINTS:
        overpass._cool(endpoint)
    assert set(overpass.cooldown_state()) == set(overpass.ENDPOINTS)

    tried = []

    def fake(query, endpoint=None, *a, **k):
        tried.append(endpoint)
        return 502, "server is currently at capacity / request queue is full"

    monkeypatch.setattr(overpass, "_http", fake)
    result = overpass.snapshot()

    assert result["status"] == overpass.DEGRADED
    assert set(tried) == set(overpass.ENDPOINTS), "a stale cooldown must not skip a mirror"
    assert result["rows"] == [] and result["signals"] == []


def test_overpass_cooldown_expires(monkeypatch):
    """A cooled mirror comes back once its window passes."""
    overpass.reset_cache()
    overpass._cool(overpass.ENDPOINTS[0])
    assert overpass._cooling(overpass.ENDPOINTS[0]) is True
    with overpass._COOLDOWN_LOCK:
        overpass._COOLDOWN[overpass.ENDPOINTS[0]] = 0.0  # pretend the window passed
    assert overpass._cooling(overpass.ENDPOINTS[0]) is False
    assert overpass._ordered_endpoints() == list(overpass.ENDPOINTS)


def test_overpass_request_ceiling_is_short_and_bounded():
    """A short per-request ceiling, sized against the measured healthy serve.

    Measured on this box: maps.mail.ru answered a one-category query in 13.9s
    while the other three mirrors did not answer inside 30s. A 20-25s ceiling is
    ~2x the healthy serve time, so a queued mirror is abandoned quickly and the
    next one is tried instead of the run waiting out the queue.
    """
    assert 20 <= overpass.MIRROR_TIMEOUT_SECONDS <= 25, "a short per-request ceiling"
    assert overpass.TIMEOUT_SECONDS == overpass.MIRROR_TIMEOUT_SECONDS
    # The whole run stays bounded even if every mirror hangs on every category.
    assert overpass.TOTAL_BUDGET_SECONDS <= 6 * overpass.MIRROR_TIMEOUT_SECONDS * 4
    assert overpass.TOTAL_BUDGET_SECONDS >= 6 * overpass.MIRROR_TIMEOUT_SECONDS
    # A politeness pause between category queries, small enough to be free.
    assert 0 < overpass.CATEGORY_DELAY_SECONDS <= 1.0
