"""THE MAPBOX ADAPTER — countable local market, not a guess.

What this does
--------------
Counts real businesses in a category inside a radius of a location, using the
Mapbox **Search Box** API, and hands the count to the signal layer. Every row is
a place Mapbox actually returned; every count is the number of rows that fell
inside the radius. Nothing is estimated, interpolated or invented.

    no credential          -> status "NEEDS KEY", reason "MAPBOX_TOKEN not set",
                              rows [], signals [], ZERO claims, NO request sent
    HTTP 401 / 402         -> "NEEDS KEY"     (invalid / absent token)
    HTTP 403               -> "NOT ENTITLED"  (the plan, not the credential)
    HTTP 429               -> "RATE LIMITED"  (back off; no count right now)
    any other non-200      -> "DEGRADED"      (literal status + body snippet)
    network failure        -> "DEGRADED"      (the literal exception text)
    200 but unparseable    -> "DEGRADED"

On every non-OK status the result carries ``businesses == []``, ``rows == []`` and
``signals == []``, and the live-data bridge turns that into zero claims. A market
you cannot measure is reported as unavailable, not as a small number.

Which endpoint, and why
-----------------------
The Search Box **category** endpoint is
``/search/searchbox/v1/category/{canonical_category_id}``. Mapbox publishes the
canonical ids, and an id that is not in their list is rejected — so this module
does NOT invent one. We could not verify an HVAC canonical id from this box, so
the DEFAULT path is the **forward** endpoint with a text query:

    GET /search/searchbox/v1/forward?q=HVAC contractor&proximity=lon,lat&limit=25

That is the documented text-query fallback, and the query is recorded alongside
the count so the number is reproducible. If a caller passes a canonical id it has
verified (``category_id="..."``), the category endpoint is used instead — the URL
builder is shared, so both paths get identical status handling.

No credential, no request
-------------------------
``secrets_vault.get("MAPBOX_TOKEN")`` (environment first, then the vault file)
decides whether a request happens at all. With no token there is nothing to
authenticate with, so the honest answer is NEEDS KEY — that is today's real state
on this box, not a failure.

The token never leaves this module
----------------------------------
It rides in the query string only. ``source_url`` is the public documentation URL,
never the request URL; every reason/error string is passed through ``_safe()``,
which strips the access_token parameter and any stored secret before the string
is returned, logged or recorded.
"""

from __future__ import annotations

import json
import logging
import math
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone

from . import secrets_vault

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

COMPONENT_NAME = "MapboxSource"

# ---------------------------------------------------------------------------
# statuses
# ---------------------------------------------------------------------------
OK = "OK"
NEEDS_KEY = "NEEDS KEY"
NOT_ENTITLED = "NOT ENTITLED"
RATE_LIMITED = "RATE LIMITED"
DEGRADED = "DEGRADED"

STATUS_ORDER = (OK, NEEDS_KEY, NOT_ENTITLED, RATE_LIMITED, DEGRADED)

#: Every status other than OK writes nothing at all.
DEGRADED_STATUSES = (NEEDS_KEY, NOT_ENTITLED, RATE_LIMITED, DEGRADED)

#: The signal a countable market emits.
MARKET_SIZE = "MARKET SIZE"

#: "Countable" starts here: five or more businesses of one category in range.
MARKET_SIZE_THRESHOLD = 5

# ---------------------------------------------------------------------------
# location + query defaults (Rochester, NY)
# ---------------------------------------------------------------------------
DEFAULT_LAT = 43.1566
DEFAULT_LON = -77.6088
DEFAULT_LABEL = "Rochester, NY"
DEFAULT_RADIUS_MILES = 50.0

#: Text query used on the forward endpoint. See the module docstring: we do not
#: invent a canonical category id we cannot verify, so the default is a text
#: query against the documented forward-search path.
DEFAULT_CATEGORY = "HVAC contractor"

#: The trades this market is counted in. One query per category, one count per
#: category. Order matters: when the same business is returned by more than one
#: query it is counted once, under the FIRST category in this tuple that matched.
CATEGORIES = (
    "HVAC contractor",
    "plumber",
    "landscaper",
    "dentist",
    "roofing contractor",
    "electrician",
)

#: The label on a per-category count signal. The signal *kind* stays MARKET SIZE
#: (the same family the single-category adapter already emits, so the bridge and
#: the UI group them together); MARKET DENSITY is the metric it reports.
MARKET_DENSITY = "MARKET DENSITY"

MAX_LIMIT = 25
DEFAULT_LIMIT = 25

TIMEOUT_SECONDS = 8.0

USER_AGENT = "jarvis-mapbox-source/1.0 (local orchestrator; +https://github.com/local/jarvis)"

CATEGORY_ENDPOINT = "https://api.mapbox.com/search/searchbox/v1/category/{category}"
FORWARD_ENDPOINT = "https://api.mapbox.com/search/searchbox/v1/forward"

#: The public documentation page cited as the source of the data. Never the
#: request URL: that one carries the access token.
SOURCE_URL = "https://docs.mapbox.com/api/search/search-box/#category-search"

COLUMNS = ("Business", "Address", "Distance", "Category")

#: The market table. Coordinates are in the row because the brief asks for them:
#: every business is a place you can drive to, not a headline.
MARKET_COLUMNS = ("Business", "Category", "Address", "Coordinates", "Distance")

EARTH_RADIUS_MILES = 3958.7613

TOKEN_NAME = "MAPBOX_TOKEN"


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


# ---------------------------------------------------------------------------
# safety: nothing that leaves here may contain the credential
# ---------------------------------------------------------------------------
def _safe(text) -> str:
    """Strip the access_token parameter and any stored secret from a string."""
    if text is None:
        return ""
    out = str(text)
    if "access_token=" in out:
        # Replace everything from the parameter to the next separator.
        parts = urllib.parse.urlsplit(out) if "://" in out else None
        if parts is not None and parts.query:
            query = urllib.parse.parse_qsl(parts.query, keep_blank_values=True)
            cleaned = [(k, ("REDACTED" if k == "access_token" else v)) for k, v in query]
            out = urllib.parse.urlunsplit(
                (parts.scheme, parts.netloc, parts.path,
                 urllib.parse.urlencode(cleaned), parts.fragment)
            )
        else:
            head, _, tail = out.partition("access_token=")
            cut = len(tail)
            for sep in ("&", " ", "\n", "\t", ",", ")"):
                pos = tail.find(sep)
                if pos != -1:
                    cut = min(cut, pos)
            out = f"{head}access_token=REDACTED{tail[cut:]}"
    return secrets_vault.scrub(out)


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


# ---------------------------------------------------------------------------
# HTTP (stdlib only)
# ---------------------------------------------------------------------------
def _http(url: str, *, headers: dict | None = None) -> tuple[int, str]:
    """One real request. Returns (status_code, body_text). Raises on network error.

    The request URL carries the token; it is never returned or logged.
    """
    req = urllib.request.Request(url, method="GET")
    req.add_header("User-Agent", USER_AGENT)
    req.add_header("Accept", "application/json")
    for key, value in (headers or {}).items():
        req.add_header(key, value)
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
            return resp.status, resp.read(200_000).decode("utf-8", "replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read(20_000).decode("utf-8", "replace")


def build_url(*, token: str, lat: float, lon: float, limit: int,
              query: str = DEFAULT_CATEGORY, category_id: str | None = None) -> str:
    """The request URL. Contains the token — never log or store the result."""
    proximity = f"{lon},{lat}"
    params = {"proximity": proximity, "limit": str(max(1, min(int(limit), MAX_LIMIT)))}
    if category_id:
        base = CATEGORY_ENDPOINT.format(
            category=urllib.parse.quote(str(category_id).strip(), safe="")
        )
    else:
        base = FORWARD_ENDPOINT
        params["q"] = str(query or DEFAULT_CATEGORY)
        params["types"] = "poi"
    params["access_token"] = token
    return f"{base}?{urllib.parse.urlencode(params)}"


# ---------------------------------------------------------------------------
# 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 _coordinates(feature: dict) -> tuple[float | None, float | None]:
    geometry = feature.get("geometry") or {}
    coords = geometry.get("coordinates")
    if isinstance(coords, (list, tuple)) and len(coords) >= 2:
        try:
            return float(coords[1]), float(coords[0])  # GeoJSON is lon,lat
        except (TypeError, ValueError):
            pass
    props = feature.get("properties") or {}
    raw = props.get("coordinates")
    if isinstance(raw, dict):
        try:
            return float(raw.get("latitude")), float(raw.get("longitude"))
        except (TypeError, ValueError):
            return None, None
    return None, None


def _address(props: dict) -> str:
    for key in ("full_address", "place_formatted", "address"):
        value = props.get(key)
        if isinstance(value, str) and value.strip():
            return value.strip()
    return "—"


def parse_features(payload: dict, *, category: str, lat: float, lon: float,
                   radius_miles: float) -> list[dict]:
    """Turn a Search Box FeatureCollection into named businesses inside the radius."""
    features = payload.get("features") if isinstance(payload, dict) else None
    if not isinstance(features, list):
        return []
    out: list[dict] = []
    for feature in features:
        if not isinstance(feature, dict):
            continue
        props = feature.get("properties") or {}
        name = (props.get("name") or props.get("name_preferred") or "").strip()
        if not name:
            continue
        flat, flon = _coordinates(feature)
        if flat is None or flon is None:
            continue
        distance = haversine_miles(lat, lon, flat, flon)
        if distance > radius_miles:
            continue
        raw_cat = props.get("poi_category") or category
        if isinstance(raw_cat, (list, tuple)):
            raw_cat = ", ".join(str(c) for c in raw_cat if str(c).strip())
        out.append({
            "name": name,
            "address": _address(props),
            "lat": round(flat, 6),
            "lon": round(flon, 6),
            "distance_miles": round(distance, 1),
            "category": str(raw_cat or category).strip() or category,
            "mapbox_id": props.get("mapbox_id") or "",
        })
    out.sort(key=lambda b: b["distance_miles"])
    return out


# ---------------------------------------------------------------------------
# results
# ---------------------------------------------------------------------------
def _result(status: str, reason: str, *, http_code=None, businesses=None,
            error: str = "", category: str = DEFAULT_CATEGORY,
            lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
            radius_miles: float = DEFAULT_RADIUS_MILES) -> dict:
    """One shape for every outcome.

    A non-OK status structurally carries zero businesses, zero rows and zero
    signals — the caller cannot accidentally convert a refusal into a claim.
    """
    businesses = list(businesses or []) if status == OK else []
    rows = [
        [b["name"], b["address"], f"{b['distance_miles']:.1f} mi", b["category"]]
        for b in businesses
    ]
    return {
        "status": status,
        "reason": _safe(reason),
        "http_code": http_code,
        "count": len(businesses),
        "businesses": businesses,
        "rows": rows,
        "columns": list(COLUMNS),
        "signals": (signals(rows=rows, columns=COLUMNS, category=category,
                           radius_miles=radius_miles)
                    if status == OK else []),
        "source_url": SOURCE_URL,
        "error": _safe(error),
        "category": category,
        "lat": lat,
        "lon": lon,
        "radius_miles": radius_miles,
        "label": DEFAULT_LABEL,
        "generated_at": _now_iso(),
    }


def _degraded(status: str, reason: str, **kwargs) -> dict:
    log.info("mapbox: %s — %s", status, _safe(reason))
    return _result(status, reason, **kwargs)


# ---------------------------------------------------------------------------
# signals
# ---------------------------------------------------------------------------
def signals(rows=None, columns=None, *, category: str | None = None,
            radius_miles: float = DEFAULT_RADIUS_MILES,
            capped: bool = False) -> list[dict]:
    """MARKET SIZE when a category has >= MARKET_SIZE_THRESHOLD businesses in range.

    Counted from the rows that were actually returned — if the rows are empty
    (a refusal, an error, or a search that found nothing) no signal is emitted.

    ``capped`` means the search returned a full page (``limit``) inside the
    radius, so the real number is a floor, not a total. The sentence then says
    "at least N" instead of claiming an exact count.
    """
    rows = list(rows or [])
    cols = [str(c).strip().lower() for c in (columns or COLUMNS)]

    def idx(name):
        for i, c in enumerate(cols):
            if c == name:
                return i
        return None

    cat_i = idx("category")
    if category:
        label = category
    elif cat_i is not None and rows and cat_i < len(rows[0]):
        label = str(rows[0][cat_i]).strip() or DEFAULT_CATEGORY
    else:
        label = DEFAULT_CATEGORY

    count = len(rows)
    if count < MARKET_SIZE_THRESHOLD:
        return []
    counting = f"at least {count}" if capped else f"{count}"
    return [{
        "kind": MARKET_SIZE,
        "metric": MARKET_DENSITY,
        "severity": "info",
        "value": count,
        "count": count,
        "capped": bool(capped),
        "category": label,
        "radius_miles": radius_miles,
        "line": (
            f"{MARKET_SIZE} — {counting} {label} businesses within "
            f"{radius_miles:g} mi of {DEFAULT_LABEL}. The market is countable, "
            f"not estimated: {counting} named places returned by Mapbox inside the radius."
        ),
    }]


# ---------------------------------------------------------------------------
# counting
# ---------------------------------------------------------------------------
def count_businesses(category: str = DEFAULT_CATEGORY, lat: float = DEFAULT_LAT,
                     lon: float = DEFAULT_LON,
                     radius_miles: float = DEFAULT_RADIUS_MILES, *,
                     limit: int = DEFAULT_LIMIT,
                     category_id: str | None = None) -> dict:
    """Count real businesses of ``category`` within ``radius_miles`` of (lat, lon).

    Returns the adapter result dict: ``status``, ``count``, ``businesses`` (name +
    address + coordinates + distance), ``rows``/``columns`` for the table, and
    ``signals`` (empty unless the count clears MARKET_SIZE_THRESHOLD).

    ``category_id`` is an optional Mapbox canonical category id the CALLER has
    verified; without it the documented forward text-query path is used.
    """
    lat = float(lat)
    lon = float(lon)
    radius_miles = float(radius_miles)

    token = secrets_vault.get(TOKEN_NAME)
    if not token:
        # No credential: send nothing, claim nothing. This is the honest answer.
        return _degraded(
            NEEDS_KEY,
            f"{TOKEN_NAME} not set — no request sent",
            category=category, lat=lat, lon=lon, radius_miles=radius_miles,
        )

    url = build_url(token=token, lat=lat, lon=lon, limit=limit,
                    query=category, category_id=category_id)
    try:
        code, text = _http(url)
    except Exception as exc:  # URLError, timeout, DNS, TLS — all the same to us
        return _degraded(
            DEGRADED,
            f"{type(exc).__name__}: {_safe(str(exc))}",
            error=f"{type(exc).__name__}: {_safe(str(exc))}",
            category=category, lat=lat, lon=lon, radius_miles=radius_miles,
        )

    if code == 401 or code == 402:
        return _degraded(NEEDS_KEY, f"HTTP {code}: {_safe(_snippet(text))}",
                         http_code=code, category=category, lat=lat, lon=lon,
                         radius_miles=radius_miles)
    if code == 403:
        return _degraded(NOT_ENTITLED, f"HTTP {code}: {_safe(_snippet(text))}",
                         http_code=code, category=category, lat=lat, lon=lon,
                         radius_miles=radius_miles)
    if code == 429:
        return _degraded(RATE_LIMITED, f"HTTP {code}: {_safe(_snippet(text))}",
                         http_code=code, category=category, lat=lat, lon=lon,
                         radius_miles=radius_miles)
    if code != 200:
        return _degraded(DEGRADED, f"HTTP {code}: {_safe(_snippet(text))}",
                         http_code=code, category=category, lat=lat, lon=lon,
                         radius_miles=radius_miles)

    try:
        payload = json.loads(text)
    except (TypeError, ValueError) as exc:
        return _degraded(
            DEGRADED, f"HTTP 200 but the body did not parse: {type(exc).__name__}",
            error=f"{type(exc).__name__}: {_safe(str(exc))}",
            http_code=code, category=category, lat=lat, lon=lon,
            radius_miles=radius_miles,
        )

    businesses = parse_features(payload, category=category, lat=lat, lon=lon,
                                radius_miles=radius_miles)
    return _result(
        OK,
        f"{len(businesses)} {category} businesses within {radius_miles:g} mi of "
        f"{DEFAULT_LABEL} ({lat}, {lon})",
        http_code=code,
        businesses=businesses,
        category=category, lat=lat, lon=lon, radius_miles=radius_miles,
    )


def signals_for(result: dict) -> list[dict]:
    """The signals for an already-computed result (used by the Live Data card)."""
    if not result or result.get("status") != OK:
        return []
    return signals(rows=result.get("rows"), columns=result.get("columns"),
                   category=result.get("category"),
                   radius_miles=result.get("radius_miles", DEFAULT_RADIUS_MILES))


# ---------------------------------------------------------------------------
# The market scan: six categories, one real count each
# ---------------------------------------------------------------------------
def scope_line(label: str = DEFAULT_LABEL,
               radius_miles: float = DEFAULT_RADIUS_MILES) -> str:
    """The scope every number on the market card is stated against."""
    return f"{label} · {radius_miles:g} mi radius"


def _business_key(business: dict) -> str:
    """Identity of one business, for de-duplication across category queries."""
    mapbox_id = str(business.get("mapbox_id") or "").strip()
    if mapbox_id:
        return f"id:{mapbox_id}"
    return "geo:{}|{}|{}|{}".format(
        str(business.get("name") or "").strip().lower(),
        str(business.get("address") or "").strip().lower(),
        business.get("lat"), business.get("lon"),
    )


def market_rows(businesses) -> list[list]:
    """The market table: one real place per row, with its coordinates."""
    return [
        [
            b["name"],
            b["category"],
            b["address"],
            f"{b['lat']:.5f}, {b['lon']:.5f}",
            f"{b['distance_miles']:.1f} mi",
        ]
        for b in (businesses or [])
    ]


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


def _market_result(status: str, reason: str, *, http_code=None,
                   businesses=None, categories=(),
                   lat: float = DEFAULT_LAT, lon: float = DEFAULT_LON,
                   radius_miles: float = DEFAULT_RADIUS_MILES,
                   limit: int = DEFAULT_LIMIT, error: str = "",
                   failed_category: str = "") -> dict:
    """The market result shape. Any non-OK status carries zero rows and signals.

    ``market.categories`` is always present so the UI can render the scope even
    when nothing could be measured — with ``count: None``, never a zero that
    would read as "we looked and found none".
    """
    ok = status == OK
    businesses = list(businesses or []) if ok else []
    if ok:
        counts = []
        for cat in categories:
            members = [b for b in businesses if b.get("matched_via") == cat]
            counts.append({
                "category": cat,
                # A full page inside the radius means the real number is a floor.
                "count": len(members),
                "capped": bool(members) and len(members) >= int(limit),
                "measured": True,
                "status": OK,
                "reason": "",
                "names": [b["name"] for b in members],
            })
        total = len(businesses)
    else:
        counts = _empty_categories(categories, status, reason)
        total = 0

    market = {
        "status": status,
        "reason": _safe(reason),
        "label": DEFAULT_LABEL,
        "lat": lat,
        "lon": lon,
        "radius_miles": radius_miles,
        "scope": scope_line(DEFAULT_LABEL, radius_miles),
        "limit": int(limit),
        "categories": counts,
        "total": total,
        "measured_categories": sum(1 for c in counts if c["measured"]),
        "failed_category": failed_category,
    }
    rows = market_rows(businesses)
    return {
        "status": status,
        "reason": _safe(reason),
        "http_code": http_code,
        "count": total,
        "businesses": businesses,
        "rows": rows,
        "columns": list(MARKET_COLUMNS),
        # A refusal has no rows, so it can emit no signal: the same structural
        # guarantee the single-category path gives.
        "signals": market_signals(market, rows=rows, columns=MARKET_COLUMNS) if ok else [],
        "market": market,
        "source_url": SOURCE_URL,
        "error": _safe(error),
        "category": ", ".join(categories[:1]) if categories else DEFAULT_CATEGORY,
        "categories": list(categories),
        "lat": lat,
        "lon": lon,
        "radius_miles": radius_miles,
        "label": DEFAULT_LABEL,
        "generated_at": _now_iso(),
    }


def market_signals(market, rows=None, columns=None) -> list[dict]:
    """One MARKET SIZE (MARKET DENSITY) signal per category, counted from rows.

    The count is the number of distinct businesses whose row carries that
    category — i.e. places Mapbox really returned inside the radius. A category
    with fewer than ``MARKET_SIZE_THRESHOLD`` businesses emits nothing, and an
    unmeasured category (a refusal) has no rows at all.
    """
    if not market or market.get("status") not in (OK, None):
        return []
    rows = list(rows or [])
    cols = [str(c).strip().lower() for c in (columns or MARKET_COLUMNS)]
    try:
        cat_i = cols.index("category")
    except ValueError:
        cat_i = 1 if len(cols) > 1 else 0
    radius = float(market.get("radius_miles", DEFAULT_RADIUS_MILES))

    out: list[dict] = []
    for entry in market.get("categories") or []:
        cat = entry.get("category")
        if not cat or not entry.get("measured", True):
            continue
        sub = [r for r in rows if cat_i < len(r) and str(r[cat_i]) == cat]
        for sig in signals(rows=sub, columns=MARKET_COLUMNS, category=cat,
                           radius_miles=radius, capped=bool(entry.get("capped"))):
            sig["scope"] = market.get("scope")
            sig["lat"] = market.get("lat")
            sig["lon"] = market.get("lon")
            sig["total_in_scope"] = len(rows)
            out.append(sig)
    return out


def count_market(categories=CATEGORIES, lat: float = DEFAULT_LAT,
                 lon: float = DEFAULT_LON,
                 radius_miles: float = DEFAULT_RADIUS_MILES, *,
                 limit: int = DEFAULT_LIMIT,
                 category_ids: dict | None = None) -> dict:
    """Count real businesses in each category within ``radius_miles`` of a point.

    One Search Box query per category (``DEFAULT_LABEL`` = Rochester, NY,
    ``DEFAULT_RADIUS_MILES`` = 50 by default). Each business the API returns is
    kept once — if two queries return the same place it is counted under the
    first category in ``categories`` that matched, so nothing is double counted
    and no count is inflated.

    Failure is all-or-nothing: if the credential is missing nothing is requested
    at all (status NEEDS KEY, zero rows, zero signals); if any one category is
    refused or errors, the market as a whole is reported with that status and
    zero rows, because a partial count presented as "the market" would be a
    claim we cannot support.
    """
    cat_list = [str(c).strip() for c in (categories or CATEGORIES) if str(c).strip()]
    lat = float(lat)
    lon = float(lon)
    radius_miles = float(radius_miles)
    ids = category_ids or {}

    token = secrets_vault.get(TOKEN_NAME)
    if not token:
        # No credential: send nothing, claim nothing, count nothing.
        return _market_result(
            NEEDS_KEY, f"{TOKEN_NAME} not set — no request sent",
            categories=cat_list, lat=lat, lon=lon, radius_miles=radius_miles,
            limit=limit,
        )

    seen: dict[str, dict] = {}
    businesses: list[dict] = []
    http_code = None
    for cat in cat_list:
        result = count_businesses(cat, lat, lon, radius_miles, limit=limit,
                                  category_id=ids.get(cat))
        if result.get("status") != OK:
            return _market_result(
                result.get("status") or DEGRADED,
                f"{cat}: {result.get('reason') or 'no result'}",
                http_code=result.get("http_code"),
                error=result.get("error") or "",
                categories=cat_list, lat=lat, lon=lon, radius_miles=radius_miles,
                limit=limit, failed_category=cat,
            )
        http_code = result.get("http_code") or http_code
        for raw in result.get("businesses") or []:
            key = _business_key(raw)
            if key in seen:
                also = seen[key].setdefault("also_matched", [])
                if cat not in also:
                    also.append(cat)
                continue
            business = dict(raw)
            business["category"] = cat          # the query that first matched it
            business["matched_via"] = cat
            business["also_matched"] = []
            seen[key] = business
            businesses.append(business)

    order = {cat: i for i, cat in enumerate(cat_list)}
    businesses.sort(key=lambda b: (order.get(b["matched_via"], 99),
                                   b["distance_miles"]))
    counts_line = ", ".join(
        f"{cat} {sum(1 for b in businesses if b['matched_via'] == cat)}"
        for cat in cat_list
    )
    return _market_result(
        OK,
        f"{len(businesses)} businesses across {len(cat_list)} categories within "
        f"{radius_miles:g} mi of {DEFAULT_LABEL} ({counts_line})",
        http_code=http_code,
        businesses=businesses,
        categories=cat_list,
        lat=lat,
        lon=lon,
        radius_miles=radius_miles,
        limit=limit,
    )
