"""THE OVERPASS ADAPTER — a countable local market with no key at all.

Why this file exists
--------------------
The Mapbox adapter needs ``MAPBOX_TOKEN``, so on a box with no credential it can
only ever report NEEDS KEY. The **Overpass API** (OpenStreetMap data) is free and
**keyless** — no signup, no token, no paid tier — so the market can be counted
instead of guessed.

    HTTP 200 + parseable JSON   -> "OK"            real rows, real per-category counts
    HTTP 429                    -> "RATE LIMITED"  literal "RATE LIMITED — HTTP 429: ..." reason
    HTTP 504 / 408              -> "TIMEOUT"       literal reason, the endpoint timed out
    any other HTTP status       -> "DEGRADED"      literal "HTTP <code>: <body>" reason
    timeout / DNS / TLS         -> "DEGRADED"      literal "<ExceptionType>: <text>"
    200 with an Overpass remark -> "DEGRADED"      the remark verbatim (e.g. timed out)
    200 but unparseable         -> "DEGRADED"      "HTTP 200 but the body did not parse: ..."

On every non-OK status the result carries ``rows == []``, ``places == []``,
``signals == []`` and ``market.categories[*].count is None`` — NOT zero. A market
we could not measure is reported as *not measured*, never as a small number, and
the live-data bridge turns that into zero claims.

The queries
-----------
One **small** Overpass QL request **per category** (six requests, one category
each), each using ``nwr[...]`` so nodes, ways and relations are all counted, and
``out center`` so a way/relation comes back with a centre coordinate:

    [out:json][timeout:25];
    nwr["shop"="hvac"](around:80467,43.1566,-77.6088);
    nwr["craft"="hvac"](around:80467,43.1566,-77.6088);
    out center 1200;

A single six-category union query is what the public endpoint 502s on under load
("server is currently at capacity / request queue is full"), so the market is
counted category by category instead: each request is cheap enough to be served
and a slow category no longer forces a full refetch.

The mirrors
-----------
The request is sent to ``ENDPOINTS`` in measured order — the responsive mirror
first, the canonical instance last — moving to the next wholly on
429/500/502/503/504 or a timeout / connection error, with a per-request ceiling
(``MIRROR_TIMEOUT_SECONDS``) so a hung mirror cannot stall the run. The endpoint
that actually answered is recorded on the result (``mirror`` / ``served_by`` /
``market.mirrors``) and is the URL the card cites; the card also states the
transport (``transport_note()``), derived from the constants rather than typed
in prose.

The cache
---------
A successful per-category result is kept under ``(category, lat, lon,
radius_miles, limit)`` for ``CACHE_TTL_SECONDS``, in memory and on disk, so a
repeat run costs nothing and one category that had to be refetched does not drag
the other five with it. Failures are never cached — a category that failed is
retried, never remembered as a failure or as a zero.

The six categories are HVAC (``shop=hvac`` OR ``craft=hvac``), plumber
(``craft=plumber``), landscaper (``craft=gardener`` OR ``shop=garden_centre``),
dentist (``amenity=dentist`` OR ``healthcare=dentist``), roofing
(``craft=roofer``) and electrician (``craft=electrician``).

A business that carries tags from two categories is counted once — de-duplicated
on OSM id *and* on name+coordinates — under the FIRST category in ``CATEGORIES``
order, exactly like the Mapbox market scan.

Which URL is cited
------------------
``source_url`` is the API endpoint that actually served the response (the card
cites it); every row additionally carries its own openable
``https://www.openstreetmap.org/{type}/{id}`` permalink, and ``query_url`` is an
Overpass-Turbo link containing the exact QL, so any count can be reproduced by a
human in a browser.
"""

from __future__ import annotations

import hashlib
import json
import logging
import math
import os
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

log = logging.getLogger("jarvis.overpass")

COMPONENT_NAME = "OverpassSource"

# ---------------------------------------------------------------------------
# statuses
# ---------------------------------------------------------------------------
OK = "OK"
RATE_LIMITED = "RATE LIMITED"
TIMEOUT = "TIMEOUT"
DEGRADED = "DEGRADED"

#: Worst-last, so a run of six queries can report its worst outcome.
STATUS_ORDER = (OK, RATE_LIMITED, TIMEOUT, DEGRADED)

# ---------------------------------------------------------------------------
# endpoints + politeness
# ---------------------------------------------------------------------------
#: The mirrors, tried in this order — ordered by MEASURED responsiveness from this
#: box on 2026-11-18, not by reputation. A one-category query (``craft=plumber``
#: or ``shop=hvac``, ~10 elements) took:
#:
#:   maps.mail.ru            200 in 13.9s / 16.2s / 16.6s   (answered every time)
#:   overpass.kumi.systems   no answer inside 30s           (queue)
#:   overpass.private.coffee no answer inside 30s           (queue)
#:   overpass-api.de         no answer inside 30s, then 502 "at capacity"
#:
#: The responsive mirror is therefore FIRST, so a healthy run is six queries at
#: ~16s each with no wasted hops. The canonical instance is LAST: it is still the
#: citation of record when nothing answered (``SOURCE_URL``), but a run no longer
#: spends its whole budget queueing behind the busiest interpreter before reaching
#: a mirror that will actually serve it.
#:
#: On 429 / 500 / 502 / 503 / 504, or a timeout / DNS / TLS failure, the next
#: mirror in this list is tried; the one that answers is recorded on the result
#: and is the URL the card and every claim cite.
ENDPOINTS: tuple[str, ...] = (
    "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",
)

#: The canonical / upstream endpoint with no mirror preference — the citation of
#: record when nothing answered at all, so a DEGRADED card never cites a mirror
#: that did not serve it.
ENDPOINT = "https://overpass-api.de/api/interpreter"

#: The public endpoint cited as the source of the data when no mirror is recorded.
SOURCE_URL = ENDPOINT

#: An Overpass-Turbo link is built from the QL so the exact query is reproducible.
QUERY_URL_BASE = "https://overpass-turbo.eu/?Q="

#: Honest identification — Overpass asks for a real, contactable User-Agent.
USER_AGENT = ("jarvis-overpass-source/1.0 (local orchestrator; "
              "+https://github.com/local/jarvis)")

#: The per-request ceiling, PER REQUEST PER MIRROR. A small one-category query is
#: cheap; the wait is queue latency, and a mirror that cannot answer a single
#: category inside this window is holding the whole run hostage.
#:
#: MEASURED on this box (2026-11-18, one-category plumber query):
#:   overpass-api.de         no answer inside 30s (queue)
#:   overpass.kumi.systems   no answer inside 30s (queue)
#:   overpass.private.coffee no answer inside 30s (queue)
#:   maps.mail.ru            200 in 13.9s
#: So ``MIRROR_TIMEOUT_SECONDS`` below is ~2x the observed healthy serve time, and
#: a mirror that blows it is failed over immediately rather than retried. The
#: run's total budget (``TOTAL_BUDGET_SECONDS``) keeps the whole page bounded.
MIRROR_TIMEOUT_SECONDS = 25.0
TIMEOUT_SECONDS = MIRROR_TIMEOUT_SECONDS

#: A short pause between category queries, so six sequential requests do not
#: arrive at a volunteer mirror as a burst. Politeness, not throttling: it is small
#: enough that six categories cost a second in total.
CATEGORY_DELAY_SECONDS = 0.4

#: Codes that mean "this instance cannot serve us right now" — move to the next
#: mirror. Anything else (200, 400, 404) is a real answer and is NOT failed over.
FAILOVER_CODES = (429, 500, 502, 503, 504)

#: How long a mirror that just failed over is skipped for the NEXT categories.
#: Without this, a mirror that hangs costs its full ceiling on every one of the six
#: queries: three dead mirrors x ``MIRROR_TIMEOUT_SECONDS`` x six categories is
#: minutes of pure waiting. With it, the first category pays for each dead mirror
#: and the rest go straight to the one that answers. Never permanent: if every
#: mirror is cooling the whole list is tried again, so a stale cooldown can never
#: mean "not attempted".
MIRROR_COOLDOWN_SECONDS = 300.0

#: Capacity responses are worth one polite retry on the SAME endpoint; a refusal
#: is not. Kept for compatibility — the mirror list is the primary resilience now.
MAX_ATTEMPTS = 2
RETRY_BACKOFF_SECONDS = 2.0
RETRYABLE_CODES = FAILOVER_CODES

#: Six sequential queries must not hang the page forever. Once this much wall
#: clock has gone, the remaining categories are reported as NOT MEASURED.
#:
#: Sized for a real run, not an unbounded one. A healthy run is six queries at
#: ~16s each (~96s) against the responsive mirror; the budget leaves room for a
#: few failover hops on top of that. Past it, the remaining categories are
#: reported as ``count: None`` with the literal reason — never as a zero — so the
#: ingest endpoint always answers in bounded time even when every mirror is down.
TOTAL_BUDGET_SECONDS = 240.0

#: How long a successful per-category response stays usable. The market changes
#: over weeks, so a repeat ingest inside a working day is free — and the cache
#: survives a process restart because it is written to disk, so a reload after a
#: deploy does not re-query a volunteer mirror for a count it already had. The
#: card always says how old a cached count is and that it was cached, so an old
#: count is never presented as a fresh one. ``cache_ttl_label()`` is the only
#: place this duration is turned into words.
CACHE_TTL_SECONDS = 6 * 60 * 60

#: Where a successful per-category response is kept between runs. One JSON file per
#: category, holding the places, the stats, the mirror that served them and the
#: wall-clock timestamp of the fetch. Only a real 200 is ever written here.
CACHE_DIR = os.environ.get(
    "JARVIS_OVERPASS_CACHE",
    os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
                 "data", "overpass_cache"))

#: How many bytes of a response we are willing to read.
MAX_BODY_BYTES = 8_000_000

# ---------------------------------------------------------------------------
# the market being counted (Rochester, NY · 50 miles)
# ---------------------------------------------------------------------------
DEFAULT_LAT = 43.1566
DEFAULT_LON = -77.6088
DEFAULT_LABEL = "Rochester, NY"
DEFAULT_RADIUS_MILES = 50.0

METERS_PER_MILE = 1609.344
EARTH_RADIUS_MILES = 3958.7613

#: The page limit on each per-category query. A full page means "at least".
ELEMENT_LIMIT = 1200

#: Each category is its own tag query: (label, ((key, value), ...)).
CATEGORIES: tuple[tuple[str, tuple[tuple[str, str], ...]], ...] = (
    ("HVAC contractor", (("shop", "hvac"), ("craft", "hvac"))),
    ("plumber", (("craft", "plumber"),)),
    ("landscaper", (("craft", "gardener"), ("shop", "garden_centre"))),
    ("dentist", (("amenity", "dentist"), ("healthcare", "dentist"))),
    ("roofer", (("craft", "roofer"),)),
    ("electrician", (("craft", "electrician"),)),
)

CATEGORY_LABELS = tuple(label for label, _tags in CATEGORIES)

#: How a category reads inside a signal sentence ("47 HVAC contractors within ...").
CATEGORY_PLURALS = {
    "HVAC contractor": "HVAC contractors",
    "plumber": "plumbers",
    "landscaper": "landscapers",
    "dentist": "dentists",
    "roofer": "roofing contractors",
    "electrician": "electricians",
}

#: The signal a countable market emits — same family the mapbox adapter uses.
MARKET_SIZE = "MARKET SIZE"
MARKET_DENSITY = "MARKET DENSITY"

#: The addressable-market signal: businesses OSM knows about that publish no
#: website. A missing ``website`` tag is a real, countable gap — not a guess.
NO_WEBSITE = "NO WEBSITE"

#: The OSM tags that count as "this business has a website".
WEBSITE_TAGS = ("website", "contact:website")

#: The row shape: one dict per real business, with its own openable permalink.
MARKET_COLUMNS = ("Business", "Address", "Lat", "Lon", "Category", "Source")


def _now_iso() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def _snippet(text: str, limit: int = 220) -> str:
    flat = " ".join(str(text or "").split())
    return flat[:limit] + ("…" if len(flat) > limit else "")


def radius_meters(radius_miles: float = DEFAULT_RADIUS_MILES) -> int:
    """Miles -> the integer metres an Overpass ``around:`` filter wants."""
    return int(round(float(radius_miles) * METERS_PER_MILE))


def scope_line(label: str = DEFAULT_LABEL,
               radius_miles: float = DEFAULT_RADIUS_MILES) -> str:
    """The scope every number on the Overpass card is stated against."""
    return f"Countable market — {label} · {radius_miles:g}-mile radius"


def cache_ttl_label(seconds: float | None = None) -> str:
    """The cache lifetime in words, derived from the constant, never typed twice.

    ``CACHE_TTL_SECONDS`` is the only place the number lives. The card, the
    registry's description and ``transport_note()`` all call this, so changing
    the constant changes every rendering of it in the same commit.
    """
    total = int(CACHE_TTL_SECONDS if seconds is None else seconds)
    if total and total % 3600 == 0:
        return f"{total // 3600}-hour"
    if total and total % 60 == 0:
        return f"{total // 60}-min"
    return f"{total}s"


def transport_note() -> str:
    """One line of transport provenance: how this count survived a loaded API.

    Distinctive on purpose — the live-data card shows it, so a reader (and a
    test) can see that the count came from a mirror-failover, per-category,
    briefly-cached fetch rather than one big query against one instance.

    Every number in the sentence is read from the constants above at call time.
    There is deliberately no literal copy of the ceiling or the TTL in this
    function: a test can monkeypatch the constants and watch the sentence move,
    which is what "cannot drift" means here.
    """
    return (f"{len(ENDPOINTS)}-mirror failover / {MIRROR_TIMEOUT_SECONDS:g}s per-query "
            f"ceiling / {cache_ttl_label()} disk cache")


def osm_url(osm_type: str, osm_id) -> str:
    """The real, openable OpenStreetMap permalink for one element."""
    return f"https://www.openstreetmap.org/{osm_type}/{osm_id}"


# ---------------------------------------------------------------------------
# HTTP
# ---------------------------------------------------------------------------
def _http(query: str, endpoint: str | None = None,
          timeout: float | None = None) -> tuple[int, str]:
    """One real POST to one Overpass interpreter. Returns (status, body).

    ``endpoint`` defaults to the canonical instance; the caller passes each
    mirror in ``ENDPOINTS`` in turn. ``timeout`` defaults to the short per-request
    ceiling, so a hung mirror can only cost that much before the next is tried;
    the caller may shorten it to whatever is left of the run budget.

    Raises on a network failure (timeout, DNS, TLS, connection reset) so
    ``_fetch()`` can move to the next mirror and ``snapshot()`` can record the
    literal exception text. Never retries by itself.
    """
    url = endpoint or ENDPOINT
    body = urllib.parse.urlencode({"data": query}).encode("utf-8")
    req = urllib.request.Request(url, data=body, method="POST")
    req.add_header("User-Agent", USER_AGENT)
    req.add_header("Accept", "application/json")
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    ceiling = float(timeout if timeout is not None else MIRROR_TIMEOUT_SECONDS)
    try:
        with urllib.request.urlopen(req, timeout=max(1.0, ceiling)) as resp:
            # A mirror can accept the connection and then trickle the body. The
            # ceiling is the whole per-request cost, not just the connect, so the
            # socket timeout is re-armed before the read as well.
            try:
                resp.fp.raw._sock.settimeout(max(1.0, ceiling))
            except Exception:  # pragma: no cover - socket internals are optional
                pass
            return resp.status, resp.read(MAX_BODY_BYTES).decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read(20_000).decode("utf-8", "replace")
    except urllib.error.URLError as exc:
        # ERRORS THAT MEAN "THIS MIRROR IS UNREACHABLE RIGHT NOW". A refused or
        # blackholed connection raises URLError, and so does a read timeout on
        # some platforms — exactly the cases the caller must fail over, so they
        # are re-raised as the plain exception and ``_fetch`` walks to the next
        # mirror instead of discarding the whole run.
        if isinstance(exc.reason, BaseException):
            raise exc.reason
        raise


def _request(query: str, endpoint: str | None = None) -> tuple[int, str]:
    """``_http`` with one polite retry on the SAME endpoint.

    Kept for callers that want a single endpoint; the probe path uses
    ``_fetch()``, which fails over to the mirrors instead of retrying a saturated
    instance.
    """
    attempts = max(1, int(MAX_ATTEMPTS))
    last_error: Exception | None = None
    for attempt in range(1, attempts + 1):
        try:
            code, text = _http(query, endpoint=endpoint)
        except Exception as exc:  # URLError, socket.timeout, DNS, TLS
            last_error = exc
            if attempt >= attempts:
                raise
            time.sleep(RETRY_BACKOFF_SECONDS * attempt)
            continue
        if code in RETRYABLE_CODES and attempt < attempts:
            log.info("overpass: HTTP %s, retrying once", code)
            time.sleep(RETRY_BACKOFF_SECONDS * attempt)
            continue
        return code, text
    if last_error is not None:  # pragma: no cover - defensive
        raise last_error
    return 0, ""  # pragma: no cover - defensive


def _host(endpoint: str) -> str:
    """``https://host/api/interpreter`` -> ``host`` — for a readable reason."""
    try:
        return urllib.parse.urlsplit(str(endpoint)).netloc or str(endpoint)
    except ValueError:  # pragma: no cover - defensive
        return str(endpoint)


def _failure_note(failures) -> str:
    """Every mirror that did not answer, one short clause each — verbatim."""
    parts = []
    for f in failures or []:
        reason = str(f.get("reason") or "").strip()
        parts.append(f"{_host(f.get('endpoint', ''))} {reason}".strip())
    return "; ".join(parts)


#: ``{endpoint: monotonic_deadline}`` — mirrors that just failed, skipped briefly.
#: A 502 or a hang is a property of the instance right now, not of the query, so
#: remembering it for a few minutes turns six sequential queries from six full
#: waits into one. Cleared by ``reset_cache()`` and never consulted when it would
#: leave no mirror to try.
_COOLDOWN: dict[str, float] = {}
_COOLDOWN_LOCK = threading.Lock()


def _cooling(endpoint: str) -> bool:
    """True while this mirror is inside its post-failure cooldown window."""
    with _COOLDOWN_LOCK:
        until = _COOLDOWN.get(endpoint)
        if until is None:
            return False
        if time.monotonic() >= until:
            _COOLDOWN.pop(endpoint, None)
            return False
        return True


def _cool(endpoint: str) -> None:
    """Skip this mirror for the next few categories — it just refused us."""
    with _COOLDOWN_LOCK:
        _COOLDOWN[endpoint] = time.monotonic() + float(MIRROR_COOLDOWN_SECONDS)


def _warm(endpoint: str) -> None:
    """This mirror just answered: it is not cooling."""
    with _COOLDOWN_LOCK:
        _COOLDOWN.pop(endpoint, None)


def cooldown_state() -> dict:
    """Which mirrors are cooling right now, in ``ENDPOINTS`` order (for the card)."""
    with _COOLDOWN_LOCK:
        now = time.monotonic()
        return {ep: round(max(0.0, until - now), 1)
                for ep, until in _COOLDOWN.items() if until > now}


def _ordered_endpoints(endpoints=None) -> list[str]:
    """The mirror list in order, minus the ones cooling — unless that empties it.

    Order is preserved exactly (main instance first, then the three mirrors), so
    the failover contract is unchanged; cooling only removes a mirror that already
    proved it cannot serve us in the last few minutes. If every mirror is cooling
    the full list is returned: a stale cooldown must never mean "not attempted".
    """
    eps = list(endpoints or ENDPOINTS)
    warm = [ep for ep in eps if not _cooling(ep)]
    return warm or eps


def _fetch(query: str, endpoints=None,
           deadline: float | None = None) -> tuple[int, str, str, list[dict]]:
    """POST one QL to each mirror in order. Returns (code, body, endpoint, failures).

    Failover rules, exactly:
      * 429 / 500 / 502 / 503 / 504, or a timeout / DNS / TLS failure -> the next
        mirror is tried immediately (no sleep: the next mirror IS the retry);
      * any other status (200, and also a 400/404 that is a real answer) is
        returned as-is — a syntax error is not fixed by asking someone else.

    When no mirror answers, the FIRST mirror's status/body is returned with an
    empty ``endpoint`` so the honest literal (e.g. "HTTP 502: server is currently
    at capacity") is what gets reported. When every mirror raised, ``code`` is 0
    and the body is the last exception text (``"URLError: ..."``).
    """
    failures: list[dict] = []
    first_code, first_text = 0, ""
    last_exc_text = ""
    for endpoint in _ordered_endpoints(endpoints):
        # Never start a request we know would overrun the run's wall-clock
        # budget: a hung mirror is skipped instead of eating the last minute.
        budget_left = None if deadline is None else deadline - time.monotonic()
        if budget_left is not None and budget_left <= 1.0:
            last_exc_text = last_exc_text or (
                "not attempted: the run's wall-clock budget was exhausted")
            failures.append({"endpoint": endpoint, "http_code": None,
                             "status": TIMEOUT,
                             "reason": "not attempted: run budget exhausted"})
            break
        try:
            code, text = _http(
                query, endpoint=endpoint,
                timeout=None if budget_left is None
                else min(MIRROR_TIMEOUT_SECONDS, budget_left),
            )
        except Exception as exc:  # timeout, DNS, TLS, connection reset
            last_exc_text = f"{type(exc).__name__}: {exc}"
            failures.append({"endpoint": endpoint, "http_code": None,
                             "status": DEGRADED, "reason": last_exc_text})
            _cool(endpoint)
            log.info("overpass: %s failed — %s", _host(endpoint),
                     _snippet(last_exc_text, 200))
            continue
        if code in FAILOVER_CODES:
            reason = f"HTTP {code}: {_snippet(text)}"
            failures.append({"endpoint": endpoint, "http_code": code,
                             "status": classify(code, text), "reason": reason})
            _cool(endpoint)
            if not first_code:
                first_code, first_text = code, text
            log.info("overpass: %s — %s, trying the next mirror",
                     _host(endpoint), _snippet(reason, 200))
            continue
        _warm(endpoint)
        if failures:
            log.info("overpass: served by %s after %d mirror failure(s)",
                     _host(endpoint), len(failures))
        return code, text, endpoint, failures
    if first_code:
        return first_code, first_text, "", failures
    return 0, last_exc_text, "", failures


def classify(code: int, text: str = "") -> str:
    """Map a real HTTP response onto one of the four honest statuses.

    429 is a rate limit, 504/408 is a timeout, anything else non-200 is DEGRADED
    with the literal status kept by the caller. A network failure never reaches
    here: ``snapshot()`` catches it and reports DEGRADED.
    """
    if code == 200:
        return OK
    if code == 429:
        return RATE_LIMITED
    if code in (504, 408):
        return TIMEOUT
    return DEGRADED


# ---------------------------------------------------------------------------
# the queries
# ---------------------------------------------------------------------------
def build_category_query(label: str, tags, lat: float = DEFAULT_LAT,
                         lon: float = DEFAULT_LON,
                         radius_miles: float = DEFAULT_RADIUS_MILES,
                         limit: int = ELEMENT_LIMIT) -> str:
    """The Overpass QL for ONE category: one ``nwr`` clause per tag pair."""
    around = f"(around:{radius_meters(radius_miles)},{float(lat):.6f},{float(lon):.6f})"
    lines = ["[out:json][timeout:25];"]
    for key, value in tags:
        lines.append(f'nwr["{key}"="{value}"]{around};')
    lines.append(f"out center {int(limit)};")
    return "\n".join(lines)


def build_query(lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
                radius_miles: float = DEFAULT_RADIUS_MILES,
                categories=CATEGORIES,
                limit: int = ELEMENT_LIMIT) -> dict[str, str]:
    """One QL per category: ``{category_label: query}``."""
    return {
        label: build_category_query(label, tags, lat, lon, radius_miles, limit)
        for label, tags in categories
    }


def union_query(lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
                radius_miles: float = DEFAULT_RADIUS_MILES,
                categories=CATEGORIES, limit: int = ELEMENT_LIMIT) -> str:
    """All six categories as one union — used only for the reproducible link."""
    around = f"(around:{radius_meters(radius_miles)},{float(lat):.6f},{float(lon):.6f})"
    lines = ["[out:json][timeout:25];", "("]
    for _label, tags in categories:
        for key, value in tags:
            lines.append(f'  nwr["{key}"="{value}"]{around};')
    lines.append(");")
    lines.append(f"out center {int(limit)};")
    return "\n".join(lines)


def query_url(query: str) -> str:
    """An Overpass-Turbo link that reproduces the exact QL in a browser."""
    return QUERY_URL_BASE + urllib.parse.quote(query, safe="")


# ---------------------------------------------------------------------------
# geometry + parsing
# ---------------------------------------------------------------------------
def haversine_miles(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    """Great-circle distance in miles. Pure math, no I/O."""
    p1, p2 = math.radians(lat1), math.radians(lat2)
    d_phi = p2 - p1
    d_lambda = math.radians(lon2 - lon1)
    a = (math.sin(d_phi / 2) ** 2
         + math.cos(p1) * math.cos(p2) * math.sin(d_lambda / 2) ** 2)
    return 2 * EARTH_RADIUS_MILES * math.asin(min(1.0, math.sqrt(a)))


def _coords(element: dict) -> tuple[float | None, float | None]:
    """Lat/lon of a node, or the centre of a way/relation (``out center``)."""
    center = element.get("center")
    if isinstance(center, dict):
        try:
            return float(center.get("lat")), float(center.get("lon"))
        except (TypeError, ValueError):
            return None, None
    try:
        return float(element.get("lat")), float(element.get("lon"))
    except (TypeError, ValueError):
        return None, None


def _name(tags: dict) -> str:
    """A business's name from OSM tags. Empty when OpenStreetMap has none."""
    for key in ("name", "operator", "brand"):
        value = tags.get(key)
        if isinstance(value, str) and value.strip():
            return value.strip()
    return ""


def _address(tags: dict) -> str:
    """``addr:*`` tags when present, else an em dash. Never invented."""
    head = ""
    number = str(tags.get("addr:housenumber") or "").strip()
    street = str(tags.get("addr:street") or "").strip()
    if number and street:
        head = f"{number} {street}"
    elif street:
        head = street
    elif number:
        head = number
    city = str(tags.get("addr:city") or "").strip()
    state = str(tags.get("addr:state") or "").strip()
    postcode = str(tags.get("addr:postcode") or "").strip()
    tail = " ".join(part for part in (city, state) if part)
    if postcode:
        tail = f"{tail} {postcode}".strip()
    parts = [part for part in (head, tail) if part]
    return ", ".join(parts) or "—"


def match_categories(tags: dict, categories=CATEGORIES) -> list[str]:
    """Which categories' tag queries this element satisfies, in CATEGORIES order."""
    if not isinstance(tags, dict):
        return []
    matched = []
    for label, pairs in categories:
        for key, value in pairs:
            if str(tags.get(key) or "") == value:
                matched.append(label)
                break
    return matched


def parse_elements(payload: dict, *, lat: float = DEFAULT_LAT,
                   lon: float = DEFAULT_LON,
                   radius_miles: float = DEFAULT_RADIUS_MILES,
                   categories=CATEGORIES) -> tuple[list[dict], dict]:
    """Turn an Overpass JSON body into named places inside the radius.

    De-duplicated by OSM id: a business carrying tags from two categories is
    counted once, under the first category in ``categories`` order (the same rule
    the mapbox market scan uses, so the two count the same way).
    """
    elements = payload.get("elements") if isinstance(payload, dict) else None
    stats = {"elements": len(elements) if isinstance(elements, list) else 0,
             "unnamed": 0, "outside_radius": 0, "duplicates": 0,
             "unmatched": 0, "unlocated": 0, "no_website": 0}
    if not isinstance(elements, list):
        return [], stats

    seen: set[str] = set()
    places: list[dict] = []
    for element in elements:
        if not isinstance(element, dict):
            continue
        osm_type = str(element.get("type") or "").strip()
        osm_id = element.get("id")
        if not osm_type or osm_id is None:
            continue
        key = f"{osm_type}/{osm_id}"
        if key in seen:
            stats["duplicates"] += 1
            continue

        tags = element.get("tags")
        if not isinstance(tags, dict):
            tags = {}
        matched = match_categories(tags, categories)
        if not matched:
            stats["unmatched"] += 1
            continue

        plat, plon = _coords(element)
        if plat is None or plon is None:
            stats["unlocated"] += 1
            continue
        distance = haversine_miles(lat, lon, plat, plon)
        if distance > radius_miles:
            stats["outside_radius"] += 1
            continue

        name = _name(tags)
        if not name:
            # A place with no name cannot be listed as a business; it is counted
            # in ``unnamed`` so the undercount is disclosed, never hidden.
            stats["unnamed"] += 1
            continue

        seen.add(key)
        has_website = any(str(tags.get(t) or "").strip() for t in WEBSITE_TAGS)
        places.append({
            "name": name,
            "category": matched[0],
            "has_website": has_website,
            "also_matched": matched[1:],
            "address": _address(tags),
            "lat": round(plat, 6),
            "lon": round(plon, 6),
            "distance_miles": round(distance, 1),
            "osm_type": osm_type,
            "osm_id": osm_id,
            "osm": key,
            "source_url": osm_url(osm_type, osm_id),
        })

    stats["no_website"] = sum(1 for p in places if not p.get("has_website"))
    order = {label: i for i, label in enumerate(label for label, _ in categories)}
    places.sort(key=lambda p: (order.get(p["category"], 99), p["distance_miles"]))
    return places, stats


def market_rows(places, mirrors: dict | None = None) -> list[dict]:
    """The market table: one real business per row, each with its own permalink.

    Row shape (as documented for this adapter):
    ``{name, address, lat, lon, category, source_url, mirror}``. ``mirror`` is the
    interpreter that actually returned THIS row's category — empty for a row read
    from the cache of a real 200, because naming a mirror for a request that was
    not made would be a guess.
    """
    mirrors = dict(mirrors or {})
    rows = []
    for p in (places or []):
        row = {
            "name": p["name"],
            "address": p["address"],
            "lat": p["lat"],
            "lon": p["lon"],
            "category": p["category"],
            "source_url": p.get("source_url") or osm_url(p["osm_type"], p["osm_id"]),
        }
        served = mirrors.get(p.get("category")) or ""
        if served:
            row["mirror"] = served
        rows.append(row)
    return rows


# ---------------------------------------------------------------------------
# the cache — one successful per-category response, kept for a few hours
# ---------------------------------------------------------------------------
#: ``{(category, lat, lon, radius_miles, limit): {places, truncated, ...}}``.
#: Warm from disk on first use (see ``CACHE_DIR``) so a restart does not cost a
#: re-query, and written back on every successful fetch. Nothing is ever
#: *reported* from the cache that was not a real 200 from a real mirror first, and
#: failures are NEVER cached nor remembered — a failed category is retried.
_CACHE: dict[tuple, dict] = {}
_CACHE_LOCK = threading.Lock()
_LOADED = False


def cache_key(category: str, lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
              radius_miles: float = DEFAULT_RADIUS_MILES,
              limit: int = ELEMENT_LIMIT) -> tuple:
    """The cache identity of one category count: category + centre + radius (+ page)."""
    return (str(category), round(float(lat), 6), round(float(lon), 6),
            round(float(radius_miles), 3), int(limit))


def _cache_file(key: tuple) -> str:
    """The on-disk file for one cache key — a stable hash, never user input."""
    blob = json.dumps(list(key), separators=(",", ":")).encode("utf-8")
    return os.path.join(CACHE_DIR, hashlib.sha256(blob).hexdigest()[:32] + ".json")


def _load_disk_cache() -> None:
    """Warm the in-memory cache from disk once per process (best effort)."""
    global _LOADED
    with _CACHE_LOCK:
        if _LOADED:
            return
        _LOADED = True
        try:
            names = [n for n in os.listdir(CACHE_DIR) if n.endswith(".json")]
        except OSError:
            return
        now = time.time()
        for name in names:
            path = os.path.join(CACHE_DIR, name)
            try:
                with open(path, "r", encoding="utf-8") as fh:
                    blob = json.load(fh)
                key = tuple(blob["key"])
                stored_at = float(blob["stored_at"])
                if now - stored_at > CACHE_TTL_SECONDS:
                    continue
                entry = dict(blob["entry"])
                entry["stored_at"] = stored_at
                entry["fetched_at"] = blob.get("fetched_at", "")
                _CACHE[key] = entry
            except (OSError, ValueError, KeyError, TypeError):
                continue


def cache_get(key: tuple) -> dict | None:
    """A still-fresh cached entry, or ``None``. Expired entries are dropped.

    The age is wall-clock (not monotonic) because the timestamp has to survive a
    process restart: a count cached before a redeploy is still a real count, and
    the card reports its age rather than pretending it was just fetched.
    """
    _load_disk_cache()
    with _CACHE_LOCK:
        entry = _CACHE.get(key)
        if not entry:
            return None
        age = time.time() - float(entry.get("stored_at", 0.0))
        if age > float(CACHE_TTL_SECONDS):
            _CACHE.pop(key, None)
            try:
                os.remove(_cache_file(key))
            except OSError:
                pass
            return None
        return dict(entry, age_seconds=round(age, 1))


def cache_put(key: tuple, entry: dict) -> None:
    """Remember ONE successful category response, in memory AND on disk.

    Only a real 200 is ever stored. The write is atomic (tmp + replace) so a
    crash mid-write cannot leave a half-JSON file that a later run would read.
    """
    _load_disk_cache()
    stored_at = time.time()
    record = dict(entry, stored_at=stored_at, fetched_at=_now_iso())
    with _CACHE_LOCK:
        _CACHE[key] = record
    try:
        os.makedirs(CACHE_DIR, exist_ok=True)
        path = _cache_file(key)
        tmp = path + ".tmp"
        with open(tmp, "w", encoding="utf-8") as fh:
            json.dump({"key": list(key), "stored_at": stored_at,
                       "fetched_at": record["fetched_at"], "entry": entry}, fh)
        os.replace(tmp, path)
    except OSError as exc:  # pragma: no cover - a read-only FS is not fatal
        log.warning("overpass: could not persist the cache entry: %s", exc)


def reset_cache() -> None:
    """Test hook / manual flush: forget every cached category count and cooldown.

    Clears the in-memory map, the on-disk files and the cooldowns, so a test that
    switches to a mocked ``_http`` is never served a previous test's real or
    mocked body.
    """
    global _LOADED
    with _CACHE_LOCK:
        _CACHE.clear()
        _LOADED = False
    try:
        for name in os.listdir(CACHE_DIR):
            if name.endswith(".json") or name.endswith(".json.tmp"):
                try:
                    os.remove(os.path.join(CACHE_DIR, name))
                except OSError:
                    pass
    except OSError:
        pass
    with _COOLDOWN_LOCK:
        _COOLDOWN.clear()


def cache_stats() -> dict:
    """How many category counts are cached right now (for the card's note)."""
    _load_disk_cache()
    with _CACHE_LOCK:
        return {"entries": len(_CACHE), "ttl_seconds": int(CACHE_TTL_SECONDS),
                "dir": CACHE_DIR}


# ---------------------------------------------------------------------------
# results
# ---------------------------------------------------------------------------
def _empty_categories(categories, status: str, reason: str) -> list[dict]:
    """One entry per category with ``count: None`` — NOT measured, not zero."""
    return [
        {
            "category": label,
            "count": None,
            "capped": False,
            "measured": False,
            "status": status,
            "reason": reason,
            "names": [],
        }
        for label, _tags in categories
    ]


def _result(status: str, reason: str, *, http_code=None, places=None,
            categories=CATEGORIES, lat: float = DEFAULT_LAT,
            lon: float = DEFAULT_LON,
            radius_miles: float = DEFAULT_RADIUS_MILES,
            limit: int = ELEMENT_LIMIT, queries: dict | None = None,
            error: str = "", category_status: dict | None = None,
            category_reason: dict | None = None,
            category_truncated: dict | None = None,
            stats: dict | None = None,
            category_mirror: dict | None = None,
            category_cached: dict | None = None,
            cache_ages: dict | None = None,
            mirror_failures=None, mirror: str = "") -> dict:
    """One shape for every outcome.

    A non-OK status structurally carries zero places, zero rows, zero signals and
    ``count: None`` per category — a refusal cannot be converted into a claim.
    """
    ok = status == OK
    places = list(places or []) if ok else []
    stats = dict(stats or {})
    category_status = dict(category_status or {})
    category_reason = dict(category_reason or {})
    category_truncated = dict(category_truncated or {})
    category_mirror = dict(category_mirror or {})
    category_cached = dict(category_cached or {})
    cache_ages = dict(cache_ages or {})
    mirror_failures = list(mirror_failures or [])

    counts = []
    for label, _tags in categories:
        cat_status = category_status.get(label, status)
        measured = cat_status == OK
        members = [p for p in places if p["category"] == label] if measured else []
        counts.append({
            "category": label,
            "count": len(members) if measured else None,
            # A full page means the real number is a floor, not a total.
            "capped": bool(category_truncated.get(label, False)),
            "measured": measured,
            "status": cat_status,
            "reason": "" if measured else category_reason.get(label, reason),
            "names": [p["name"] for p in members],
            # Provenance: which mirror actually served this category (or that it
            # came from the short-lived cache of a real 200).
            "mirror": category_mirror.get(label, "") if measured else "",
            "cached": bool(category_cached.get(label, False)),
            # How old a cached count is, so an old number is never read as fresh.
            "cache_age_seconds": round(float(cache_ages.get(label, 0.0)), 1)
            if category_cached.get(label) else 0.0,
        })

    total = len(places) if ok else 0
    truncated = any(c["capped"] for c in counts)
    queries = dict(queries or {})
    turbo = query_url(union_query(lat, lon, radius_miles, categories, limit))
    measured_categories = sum(1 for c in counts if c["measured"])
    # Which mirror answered: the one that served the most categories, else the
    # one passed in, else the canonical endpoint when nothing answered at all.
    served: dict[str, str] = {}
    for c in counts:
        if c["measured"] and c["mirror"]:
            served[c["mirror"]] = served.get(c["mirror"], 0) + 1
    served_endpoint = (max(served, key=served.get) if served
                       else (mirror or (ENDPOINT if ok else "")))
    cited_url = served_endpoint or ENDPOINT

    market = {
        "status": status,
        "reason": reason,
        "label": DEFAULT_LABEL,
        "lat": lat,
        "lon": lon,
        "radius_miles": radius_miles,
        "radius_meters": radius_meters(radius_miles),
        "scope": scope_line(DEFAULT_LABEL, radius_miles),
        "limit": int(limit),
        "categories": counts,
        "total": total,
        "no_website": int(stats.get("no_website", 0)) if ok else 0,
        "measured_categories": measured_categories,
        # Partial is fine: some categories answered, some did not. The card says
        # so and the failed ones stay count: None with their literal reason.
        "partial": bool(ok and 0 < measured_categories < len(counts)),
        "failed_categories": [c["category"] for c in counts if not c["measured"]],
        "truncated": truncated,
        "stats": stats,
        "endpoint": cited_url,
        "mirror": served_endpoint,
        # Which mirror actually served the bytes (host only, for display).
        "served_by": _host(served_endpoint) if served_endpoint else "",
        "mirror_count": len(ENDPOINTS),
        "mirror_timeout_seconds": MIRROR_TIMEOUT_SECONDS,
        "transport": transport_note(),
        # The TTL in words, derived from CACHE_TTL_SECONDS by the adapter so the
        # template never has to divide by 3600 (or claim "hour" for a 15-min TTL).
        "cache_ttl_label": cache_ttl_label(),
        # The exact order tried, so the card's "N-mirror failover" is verifiable.
        "endpoints": list(ENDPOINTS),
        "mirror_order": [_host(ep) for ep in ENDPOINTS],
        "mirrors": dict(category_mirror),
        "mirror_failures": mirror_failures,
        "cached": dict(category_cached),
        "cached_categories": [c["category"] for c in counts if c["cached"]],
        "cached_any": any(c["cached"] for c in counts),
        "cache_age_seconds": round(max((c["cache_age_seconds"] for c in counts),
                                       default=0.0), 1),
        "cache": cache_stats(),
        "cache_ttl_seconds": int(CACHE_TTL_SECONDS),
        "endpoints": list(ENDPOINTS),
        "queries": queries,
        "query_url": turbo,
    }
    rows = market_rows(places, category_mirror)
    return {
        "status": status,
        "reason": reason,
        "http_code": http_code,
        "count": total,
        "places": places,
        "rows": rows,
        "columns": list(MARKET_COLUMNS),
        # No rows -> no signals, structurally.
        "signals": _signals(rows=rows, columns=MARKET_COLUMNS, market=market) if ok else [],
        "market": market,
        # The URL that actually served this count — the mirror, not a guess.
        "source_url": cited_url,
        "mirror": served_endpoint,
        "served_by": market["served_by"],
        "transport": market["transport"],
        "mirrors": dict(category_mirror),
        "mirror_failures": mirror_failures,
        "cached": dict(category_cached),
        "cached_any": market["cached_any"],
        "cache_ttl_seconds": market["cache_ttl_seconds"],
        "cache_ttl_label": market["cache_ttl_label"],
        "query_url": turbo,
        "error": error,
        "queries": queries,
        "categories": [label for label, _tags in categories],
        "lat": lat,
        "lon": lon,
        "radius_miles": radius_miles,
        "label": DEFAULT_LABEL,
        "scope": market["scope"],
        "generated_at": _now_iso(),
    }


def _degraded(reason: str, **kwargs) -> dict:
    log.info("overpass: %s — %s", DEGRADED, _snippet(reason, 400))
    return _result(DEGRADED, reason, **kwargs)


# ---------------------------------------------------------------------------
# signals
# ---------------------------------------------------------------------------
def _signals(rows=None, columns=None, *, market=None,
             radius_miles: float = DEFAULT_RADIUS_MILES,
             label: str = DEFAULT_LABEL) -> list[dict]:
    """One MARKET SIZE (MARKET DENSITY) signal per category that has results.

    Pure: the count is the number of distinct named places whose row carries that
    category. A category that was never measured (a refusal, zero rows) has
    nothing to count, so a failure can never emit a signal. A category whose
    response filled the page limit is labelled "at least N". The threshold is one
    business, not five: a measured count of 1..4 is a real count and is reported
    as such (only a count of 0, or an unmeasured category, emits nothing).
    """
    rows = list(rows or [])
    cols = [str(c).strip().lower() for c in (columns or MARKET_COLUMNS)]

    # The URL cited is the mirror that actually served the count; the canonical
    # endpoint is only cited when no mirror is known (a cached/older capture).
    cited = SOURCE_URL
    if market is not None:
        if market.get("status") not in (OK, None):
            return []
        categories = market.get("categories") or []
        radius_miles = float(market.get("radius_miles", radius_miles))
        scope = market.get("scope") or scope_line(label, radius_miles)
        cited = market.get("endpoint") or SOURCE_URL
    else:
        # No market block: derive counts from the rows alone (dict or list rows).
        def row_category(row):
            if isinstance(row, dict):
                return str(row.get("category") or "")
            try:
                i = cols.index("category")
            except ValueError:
                i = 1
            return str(row[i]) if i < len(row) else ""

        def row_name(row):
            if isinstance(row, dict):
                return str(row.get("name") or "")
            return str(row[0]) if row else ""

        categories = []
        for cat in CATEGORY_LABELS:
            sub = [r for r in rows if row_category(r) == cat]
            categories.append({"category": cat, "count": len(sub),
                               "capped": False, "measured": True,
                               "names": [row_name(r) for r in sub]})
        scope = scope_line(label, radius_miles)

    out: list[dict] = []
    no_website = 0
    if market is not None and market.get("status") in (OK, None):
        no_website = int(market.get("no_website") or 0)
    for entry in categories:
        cat = entry.get("category")
        if not cat or not entry.get("measured", True):
            continue
        count = entry.get("count")
        if count is None or count <= 0:
            continue
        capped = bool(entry.get("capped", False))
        counting = f"at least {count}" if capped else f"{count}"
        plural = CATEGORY_PLURALS.get(cat, cat)
        out.append({
            "kind": MARKET_SIZE,
            "metric": MARKET_DENSITY,
            "severity": "info",
            "value": count,
            "count": count,
            "capped": capped,
            "category": cat,
            "radius_miles": radius_miles,
            "scope": scope,
            "source_url": cited,
            "line": (
                f"{MARKET_SIZE} — {counting} {plural} within "
                f"{radius_miles:g} miles of {label}. The market is countable, not "
                f"estimated: {counting} named places returned by the OpenStreetMap "
                f"Overpass API inside the radius."
            ),
        })

    # -- the addressable-market signal: businesses with no website tag --------
    if no_website > 0:
        out.append({
            "kind": NO_WEBSITE,
            "severity": "info",
            "value": no_website,
            "count": no_website,
            "radius_miles": radius_miles,
            "scope": scope,
            "source_url": cited,
            "line": (
                f"{NO_WEBSITE} — {no_website} of the counted businesses within "
                f"{radius_miles:g} miles of {label} publish no website tag in "
                f"OpenStreetMap. A missing website is a countable, addressable gap: "
                f"these are real local businesses with no web presence recorded."
            ),
        })
    return out


def market_signals(market, rows=None, columns=None) -> list[dict]:
    """Alias kept parallel to ``mapbox_source.market_signals``."""
    return _signals(rows=rows, columns=columns, market=market)


# ---------------------------------------------------------------------------
# the probe
# ---------------------------------------------------------------------------
def _snapshot_single(lat: float, lon: float, radius_miles: float,
                     categories, limit: int) -> dict:
    """ONE union request for every category — the OPT-IN path.

    A single union query (``( nwr[...]; nwr[...]; ... ); out center;``) returns
    every matching element in one response. That is what the loaded public
    endpoint answers with 502 "server is currently at capacity / request queue is
    full", so it is no longer the default: it is kept for comparison and for the
    reproducible Overpass-Turbo link. It still fails over across the mirrors.
    """
    query = union_query(lat, lon, radius_miles, categories, limit)
    queries = {label: query for label, _tags in categories}
    code, text, endpoint, failures = _fetch(query)

    if code == 0:
        reason = text or "no mirror answered"
        log.info("overpass: DEGRADED — %s", _snippet(reason, 400))
        return _result(DEGRADED, reason, categories=categories, lat=lat, lon=lon,
                       radius_miles=radius_miles, limit=limit, queries=queries,
                       error=reason, mirror_failures=failures)

    status = classify(code, text)
    if status != OK:
        literal = f"HTTP {code}: {_snippet(text)}"
        reason = f"{status} — {literal}" if status != DEGRADED else literal
        if failures:
            reason += f" (mirrors tried: {_failure_note(failures)})"
        log.info("overpass: %s — %s", status, _snippet(reason, 400))
        return _result(status, reason, http_code=code, categories=categories,
                       lat=lat, lon=lon, radius_miles=radius_miles, limit=limit,
                       queries=queries, error=reason, mirror_failures=failures)

    try:
        payload = json.loads(text)
    except (TypeError, ValueError):
        reason = f"HTTP 200 but the body did not parse: {_snippet(text)}"
        log.info("overpass: DEGRADED — %s", _snippet(reason, 400))
        return _result(DEGRADED, reason, http_code=code, categories=categories,
                       lat=lat, lon=lon, radius_miles=radius_miles, limit=limit,
                       queries=queries, error=reason)
    if not isinstance(payload, dict):
        reason = f"HTTP 200 but the body did not parse: {_snippet(text)}"
        return _result(DEGRADED, reason, http_code=code, categories=categories,
                       lat=lat, lon=lon, radius_miles=radius_miles, limit=limit,
                       queries=queries, error=reason)

    remark = str(payload.get("remark") or "").strip()
    if remark:
        reason = f"Overpass remark: {remark}"
        log.info("overpass: DEGRADED — %s", _snippet(reason, 400))
        return _result(DEGRADED, reason, http_code=code, categories=categories,
                       lat=lat, lon=lon, radius_miles=radius_miles, limit=limit,
                       queries=queries, error=reason)

    elements = payload.get("elements")
    if not isinstance(elements, list):
        elements = []

    # A response that fills the page limit is a floor for EVERY category, because
    # the cap is on the whole union response, not on one category.
    capped = len(elements) >= int(limit)
    category_status = {label: OK for label, _tags in categories}
    category_truncated = {label: capped for label, _tags in categories}

    places, stats = parse_elements({"elements": elements}, lat=lat, lon=lon,
                                   radius_miles=radius_miles, categories=categories)

    counts_line = ", ".join(
        f"{label} {sum(1 for p in places if p['category'] == label)}"
        for label, _tags in categories
    )
    reason = (f"{len(places)} businesses across {len(categories)} categories within "
              f"{radius_miles:g} mi of {DEFAULT_LABEL} ({counts_line}) — one Overpass "
              f"union query, {len(elements)} element(s) returned")
    if capped:
        reason += (f" — the response hit the {int(limit)}-element page limit, so every "
                   f"count is a floor (at least N)")
    return _result(OK, reason, http_code=code, places=places,
                   categories=categories, lat=lat, lon=lon,
                   radius_miles=radius_miles, limit=limit, queries=queries,
                   category_status=category_status,
                   category_reason={},
                   category_truncated=category_truncated, stats=stats)


def _snapshot_per_category(lat: float, lon: float, radius_miles: float,
                           categories, limit: int,
                           use_cache: bool = True) -> dict:
    """One SMALL request per category, each failed over across the mirrors.

    This is the default path: six cheap queries instead of one union query that a
    loaded endpoint 502s on, every one of them tried against ``ENDPOINTS`` in
    order, and every success kept in the short-lived cache.

    Partial failure is fine and is reported as such: the categories that answered
    carry their real counts, the ones that did not carry ``count: None`` with the
    literal reason — never a fabricated number. Only when NO category could be
    measured is the whole source non-OK, which means zero places, zero rows and
    zero signals reaching the bridge.
    """
    queries = build_query(lat, lon, radius_miles, categories, limit=limit)

    started = time.monotonic()
    places: list[dict] = []
    seen_ids: set[str] = set()
    seen_keys: set[tuple] = set()
    category_status: dict[str, str] = {}
    category_reason: dict[str, str] = {}
    category_truncated: dict[str, bool] = {}
    category_mirror: dict[str, str] = {}
    category_cached: dict[str, bool] = {}
    cache_ages: dict[str, float] = {}
    mirror_failures: list[dict] = []
    totals = {"elements": 0, "unnamed": 0, "outside_radius": 0,
              "duplicates": 0, "unmatched": 0, "unlocated": 0, "no_website": 0}
    worst: str | None = None
    http_code = None
    served_endpoint = ""

    def note_failure(label: str, status: str, reason: str) -> None:
        nonlocal worst
        category_status[label] = status
        category_reason[label] = reason
        if worst is None or STATUS_ORDER.index(status) > STATUS_ORDER.index(worst):
            worst = status

    def merge(label: str, found: list[dict]) -> None:
        """Add one category's places, de-duplicated across categories.

        De-dupe is on OSM id AND on name+coordinates, so a business tagged in two
        categories is counted once — under the FIRST category in ``categories``
        order, exactly as before.
        """
        for place in found:
            key = (place["name"].strip().lower(),
                   round(place["lat"], 4), round(place["lon"], 4))
            if place["osm"] in seen_ids or key in seen_keys:
                totals["duplicates"] += 1
                continue
            seen_ids.add(place["osm"])
            seen_keys.add(key)
            places.append(place)

    queried = 0
    for label, tags in categories:
        key = cache_key(label, lat, lon, radius_miles, limit)

        # -- 1. a fresh cached success makes this category free ----------------
        if use_cache:
            hit = cache_get(key)
            if hit:
                category_status[label] = OK
                category_reason[label] = ""
                category_truncated[label] = bool(hit.get("truncated"))
                category_mirror[label] = str(hit.get("endpoint") or "")
                category_cached[label] = True
                cache_ages[label] = float(hit.get("age_seconds") or 0.0)
                for stat, value in (hit.get("stats") or {}).items():
                    if stat == "no_website":
                        continue
                    totals[stat] = totals.get(stat, 0) + int(value or 0)
                merge(label, list(hit.get("places") or []))
                continue

        # -- 2. the wall-clock budget ----------------------------------------
        if time.monotonic() - started > TOTAL_BUDGET_SECONDS:
            note_failure(label, DEGRADED,
                         f"not measured: the {TOTAL_BUDGET_SECONDS:.0f}s budget for the "
                         f"category queries was exhausted")
            continue

        # -- 3. one small query, failed over across every mirror -------------
        # A short pause between NETWORK queries only: a cache hit costs nothing
        # and must not be slowed down, and the first query fires immediately.
        if queried and CATEGORY_DELAY_SECONDS > 0:
            time.sleep(float(CATEGORY_DELAY_SECONDS))
        queried += 1
        code, text, endpoint, failures = _fetch(
            queries[label], deadline=started + TOTAL_BUDGET_SECONDS)
        mirror_failures.extend(dict(post=label, **f) for f in failures)
        if endpoint:
            served_endpoint = served_endpoint or endpoint

        if code == 0:
            # Every mirror raised (timeout / DNS / TLS): the literal last error.
            literal = text or "no mirror answered"
            note_failure(label, DEGRADED, literal)
            continue

        http_code = code if http_code is None else http_code
        status = classify(code, text)
        if status != OK:
            literal = f"HTTP {code}: {_snippet(text)}"
            note = (f"{status} — {literal}" if status != DEGRADED else literal)
            if failures:
                note += f" (mirrors tried: {_failure_note(failures)})"
            note_failure(label, status, note)
            continue

        try:
            payload = json.loads(text)
        except (TypeError, ValueError):
            note_failure(label, DEGRADED,
                         f"HTTP 200 but the body did not parse: {_snippet(text)}")
            continue
        if not isinstance(payload, dict):
            note_failure(label, DEGRADED,
                         f"HTTP 200 but the body did not parse: {_snippet(text)}")
            continue

        remark = str(payload.get("remark") or "").strip()
        if remark:
            note_failure(label, DEGRADED, f"Overpass remark: {remark}")
            continue

        elements = payload.get("elements")
        if not isinstance(elements, list):
            elements = []
        truncated = len(elements) >= int(limit)
        category_truncated[label] = truncated
        category_status[label] = OK
        category_reason[label] = ""
        category_mirror[label] = endpoint
        category_cached[label] = False
        cache_ages.pop(label, None)

        found, stats = parse_elements({"elements": elements}, lat=lat, lon=lon,
                                      radius_miles=radius_miles,
                                      categories=((label, tags),))
        for stat, value in stats.items():
            if stat == "no_website":
                continue  # recomputed from the de-duplicated places below
            totals[stat] = totals.get(stat, 0) + int(value or 0)

        # Only a real 200 is ever cached — never a failure, never a zero.
        if use_cache:
            cache_put(key, {"places": found, "truncated": truncated,
                            "stats": {k: v for k, v in stats.items()
                                      if k != "no_website"},
                            "elements": len(elements), "endpoint": endpoint,
                            "label": label})
        merge(label, found)

    totals["no_website"] = sum(1 for p in places if not p.get("has_website"))

    measured = [label for label, _tags in categories
                if category_status.get(label) == OK]
    provenance = {"category_mirror": category_mirror,
                  "category_cached": category_cached,
                  "cache_ages": cache_ages,
                  "mirror_failures": mirror_failures,
                  "mirror": served_endpoint}

    # -- ALL categories failed: the source itself is not measured -------------
    if not measured:
        status = worst or DEGRADED
        reasons = [f"{label}: {category_reason.get(label, '')}"
                   for label, _tags in categories if category_reason.get(label)]
        reason = "; ".join(reasons) or "no category could be measured"
        tried = sorted({str(f.get("endpoint") or "") for f in mirror_failures})
        tried = [ep for ep in tried if ep]
        if tried:
            reason += (f" — all {len(tried)} mirror(s) failed "
                       f"({', '.join(_host(ep) for ep in tried)}); "
                       f"0 of {len(categories)} categories measured, 0 claims written")
        log.info("overpass: %s — %s", status, _snippet(reason, 400))
        return _result(status, reason, http_code=http_code, categories=categories,
                       lat=lat, lon=lon, radius_miles=radius_miles, limit=limit,
                       queries=queries, error=reason,
                       category_status=category_status,
                       category_reason=category_reason,
                       category_truncated=category_truncated, stats=totals,
                       **provenance)

    # -- some (or all) answered: report exactly that -------------------------
    counts_line = ", ".join(
        f"{label} {sum(1 for p in places if p['category'] == label)}"
        for label, _tags in categories if category_status.get(label) == OK
    )
    reason = (f"{len(places)} businesses across {len(measured)} of {len(categories)} "
              f"categories within {radius_miles:g} mi of {DEFAULT_LABEL} "
              f"({counts_line})")
    if served_endpoint:
        reason += f" — served by {_host(served_endpoint)}"
    cached_labels = [label for label, _tags in categories if category_cached.get(label)]
    if cached_labels:
        reason += f" — {len(cached_labels)} category count(s) from cache"
    capped = [label for label, _tags in categories if category_truncated.get(label)]
    if capped:
        reason += (f" — {', '.join(capped)} hit the {int(limit)}-element page limit, "
                   f"so those counts are a floor (at least N)")
    failed = [f"{label}: {category_reason.get(label, '')}"
              for label, _tags in categories if category_status.get(label) != OK]
    if failed:
        reason += f" — not measured: {'; '.join(failed)}"
    log.info("overpass: OK — %s", _snippet(reason, 400))
    return _result(OK, reason, http_code=http_code, places=places,
                   categories=categories, lat=lat, lon=lon,
                   radius_miles=radius_miles, limit=limit, queries=queries,
                   category_status=category_status,
                   category_reason=category_reason,
                   category_truncated=category_truncated, stats=totals,
                   **provenance)


def snapshot(lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
             radius_miles: float = DEFAULT_RADIUS_MILES,
             categories=CATEGORIES, *, limit: int = ELEMENT_LIMIT,
             per_category: bool = True, use_cache: bool = True) -> dict:
    """Query Overpass for real and report exactly what came back.

    Keyless: there is no credential branch.

    The default path is one **small query per category**, each failed over across
    ``ENDPOINTS`` (main instance, then three public mirrors) on 429/500/502/503/504
    or a timeout, with a 25s ceiling per request, and each success cached for
    ``CACHE_TTL_SECONDS`` under ``(category, centre, radius, limit)``. That is what
    survives the "server is currently at capacity / request queue is full" 502 the
    single six-category union query keeps getting, and it lets six categories be
    reported independently: some measured, some ``count: None`` with the literal
    reason, and only an all-fail run degrades the source.

    ``per_category=False`` still offers the old one-union-query path (kept for the
    reproducible link and for comparison); it is no longer the default because the
    public endpoint chokes on it.

    On a total failure the result carries zero places, zero rows and zero signals,
    and the literal reason the mirrors gave — a refusal is never converted to a
    claim.
    """
    categories = tuple(categories or CATEGORIES)
    lat = float(lat)
    lon = float(lon)
    radius_miles = float(radius_miles)
    if per_category:
        return _snapshot_per_category(lat, lon, radius_miles, categories, limit,
                                      use_cache=use_cache)
    return _snapshot_single(lat, lon, radius_miles, categories, limit)


def count_market(lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
                 radius_miles: float = DEFAULT_RADIUS_MILES,
                 categories=CATEGORIES) -> dict:
    """Documented alias for ``snapshot()`` — the market count, counted live."""
    return snapshot(lat=lat, lon=lon, radius_miles=radius_miles,
                    categories=categories)
