"""THE LIVE DATA LAYER — twelve real API adapters, honest status, no fakes.

What this is
------------
A registry of twelve external data adapters that feed the JARVIS loop, plus a
probe that actually calls each one and classifies the *real* HTTP response.

Two of them need no credential at all — ``overpass`` (OpenStreetMap business
counts) and ``open_meteo`` (weather) — so they are LIVE on a box with no keys.
The other nine keep their honest NEEDS KEY / NOT ENTITLED / DEGRADED status;
``groq`` is one of those, gated by the vault and probed for real.

Status is DERIVED, never asserted
---------------------------------
Every badge on the page is the outcome of the most recent recorded check:

    LIVE          the adapter returned real, parseable data (HTTP 200)
    NEEDS KEY     the endpoint answered, but refused us for want of a credential
                  (HTTP 401 / 402, or a 403 that is not an entitlement refusal)
    NOT ENTITLED  the endpoint answered and rejected the *plan* (HTTP 403 with an
                  entitlement message, e.g. "not entitled ... upgrade your plan")
    DEGRADED      the keyless adapters answered with an error, a rate limit, a
                  timeout or a body that did not parse — literal reason kept
    ERROR         network failure, timeout, or a body we could not parse

There is no code path that sets a status by hand. ``probe()`` returns the status
and the raw evidence (http code + first bytes of the body) that produced it, and
the page renders that evidence next to the badge so the claim is checkable.

Seeded captures
---------------
The eight rows below were captured on 2026-11-18 and are stored as ordinary
probe results with their real timestamps, source URLs and payloads. They are
labelled with their capture date everywhere they are shown. Re-running the
probe appends new results; it never rewrites or deletes the old ones, so a
capture that succeeded this morning still shows as a capture that succeeded this
morning even if the credential is gone this afternoon.

Every probe run writes to the hash-chained audit ledger: one row per source
(``live_data.probe``) plus one run summary (``live_data.probe_run``).
"""

from __future__ import annotations

import json
import logging
import os
import threading
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone

from . import audit
from . import groq_source
from . import mapbox_source
from . import open_meteo
from . import overpass
from . import tavily_source

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

COMPONENT_NAME = "LiveDataLayer"

#: The day the seeded captures were taken. Shown on every seeded row.
CAPTURE_DATE = "2026-11-18"

#: Honest identification to every endpoint we touch.
USER_AGENT = "jarvis-live-data/1.0 (local orchestrator; +https://github.com/local/jarvis)"

#: Per-request ceiling. A slow endpoint is an ERROR, not a hang.
TIMEOUT_SECONDS = 8.0

#: How many probe results the in-memory capture log keeps.
CAPTURE_LOG_LIMIT = 200

LIVE = "LIVE"
NEEDS_KEY = "NEEDS KEY"
NOT_ENTITLED = "NOT ENTITLED"
#: The keyless adapters (overpass, open_meteo) report a failed call as DEGRADED
#: with the literal HTTP status / exception text. It is a refusal for citation
#: purposes: zero rows, zero signals, zero claims.
DEGRADED = "DEGRADED"
ERROR = "ERROR"

STATUS_ORDER = (LIVE, NEEDS_KEY, NOT_ENTITLED, DEGRADED, ERROR)

#: The literal, verbatim reason Massive gives us. Never paraphrased, never faked.
MASSIVE_NOT_ENTITLED_REASON = "HTTP 403: not entitled to this data — plan upgrade required"

#: Substrings that mean "your plan does not include this", not "you forgot a key".
ENTITLEMENT_MARKERS = (
    "not entitled",
    "upgrade your plan",
    "upgrade your subscription",
    "plan does not",
    "does not include",
    "subscription required",
    "insufficient permissions for this plan",
    "tier",
)


# ---------------------------------------------------------------------------
# HTTP
# ---------------------------------------------------------------------------
def _http(url: str, *, headers: dict | None = None, method: str = "GET",
          body: bytes | None = None) -> tuple[int, str]:
    """One real request. Returns (status_code, body_text). Raises on network error."""
    req = urllib.request.Request(url, data=body, method=method)
    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 classify(code: int, text: str) -> str:
    """Map a real HTTP response onto one of the four honest statuses."""
    if code == 200:
        return LIVE
    if code in (401, 402):
        return NEEDS_KEY
    if code == 403:
        low = (text or "").lower()
        if any(marker in low for marker in ENTITLEMENT_MARKERS):
            return NOT_ENTITLED
        return NEEDS_KEY
    return ERROR


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


def _result(status: str, detail: str, *, http_code=None, rows=None,
            columns=None, source_url: str = "", error: str = "",
            market=None, payload=None, result_count=None) -> dict:
    return {
        "status": status,
        "detail": detail,
        "http_code": http_code,
        # The real result count when the adapter reports one (Tavily), else the
        # row count, so a card can never show a count with no evidence behind it.
        "result_count": (result_count if result_count is not None
                         else (len(rows) if rows else 0)),
        "rows": rows or [],
        "columns": columns or [],
        "source_url": source_url,
        "error": error,
        # Only the mapbox/overpass adapters have one: the per-category count
        # breakdown.
        "market": market,
        # The structured payload behind the rows, when the adapter computes its
        # signals from numbers rather than display strings (open_meteo's daily
        # arrays). ``None`` for every adapter that does not need it.
        "payload": payload,
    }


# ---------------------------------------------------------------------------
# Derived signals — computed from the REAL rows, never asserted by hand.
# ---------------------------------------------------------------------------
#: A used-car listing older than this many days on market is stale inventory.
STALE_DOM_DAYS = 120


def _signals(source_id: str, rows, columns, market=None, payload=None,
             source_url: str = "") -> list[dict]:
    """Turn real captured rows into named signals. Pure function, no I/O.

    Nothing here invents a signal: if the rows do not contain the field the rule
    needs, the rule returns nothing.

    ``market`` is the mapbox/overpass per-category breakdown (``None`` for every
    other source and for captures recorded before it existed). When it is present
    and OK, the density signals are computed one per category from the rows.
    ``payload`` is the open_meteo daily arrays, and ``source_url`` is the URL the
    capture cited — both only used by the adapters that need them.
    """
    out: list[dict] = []
    cols = [str(c).strip().lower() for c in (columns or [])]
    rows = rows or []

    def idx(*names):
        for i, c in enumerate(cols):
            if c in names:
                return i
        return None

    if source_id == "marketcheck":
        dom_i = idx("days on market", "dom", "days_on_market")
        vin_i = idx("vin")
        veh_i = idx("vehicle", "car", "title")
        price_i = idx("price")
        if dom_i is not None:
            for row in rows:
                try:
                    dom = int(str(row[dom_i]).strip())
                except (ValueError, TypeError, IndexError):
                    continue
                if dom > STALE_DOM_DAYS:
                    def cell(i):
                        return row[i] if i is not None and i < len(row) else "—"
                    out.append({
                        "kind": "STALE INVENTORY",
                        "severity": "warn",
                        "value": dom,
                        "vehicle": cell(veh_i),
                        "vin": cell(vin_i),
                        "price": cell(price_i),
                        "line": (f"STALE INVENTORY — {cell(veh_i)} (VIN {cell(vin_i)}) has been "
                                 f"on market {dom} days, over the {STALE_DOM_DAYS}-day threshold. "
                                 f"Re-pricing pressure is a live opportunity."),
                    })

    elif source_id == "xweather":
        p_i = idx("precip", "precipitation", "precip chance", "pop")
        d_i = idx("date", "day")
        if p_i is not None and rows:
            vals: list[float | None] = []
            for row in rows:
                raw = str(row[p_i]).strip().replace("%", "").replace("in", "").strip()
                try:
                    vals.append(float(raw))
                except ValueError:
                    vals.append(None)
            stretch = 0
            for v in vals:
                if v is not None and v <= 0:
                    stretch += 1
                else:
                    break
            if stretch >= 2:
                days = [str(r[d_i]) for r in rows[:stretch]] if d_i is not None else []
                out.append({
                    "kind": "DEMAND DIP",
                    "severity": "warn",
                    "value": stretch,
                    "line": (f"DEMAND DIP — {stretch} consecutive days at 0% precipitation"
                             + (f" ({', '.join(days)})" if days else "")
                             + ". No storm-driven roofing/restoration demand, and mild, dry days "
                               "suppress heating calls. Outdoor trades should expect a demand dip."),
                })

    elif source_id == "mapbox":
        # A countable market fires one MARKET SIZE (MARKET DENSITY) signal per
        # MEASURED category with at least one business in range. Computed from
        # the rows it really returned, so a refusal (zero rows) can never emit
        # a signal — and a category that was never measured cannot either.
        if market and (market.get("status") in (None, mapbox_source.OK)):
            out.extend(mapbox_source.market_signals(market, rows=rows, columns=columns))
        else:
            out.extend(mapbox_source.signals(
                rows=rows, columns=columns,
                radius_miles=mapbox_source.DEFAULT_RADIUS_MILES,
            ))

    elif source_id == "financial_datasets":
        for row in rows[:5]:
            title = row[0] if row else ""
            src = row[1] if len(row) > 1 else "—"
            date = row[2] if len(row) > 2 else "—"
            if not title:
                continue
            out.append({
                "kind": "TREND",
                "severity": "info",
                "line": f"TREND — {title} ({src}, {date})",
            })

    elif source_id == "overpass":
        # A countable market with no key at all. One MARKET SIZE (MARKET DENSITY)
        # signal per MEASURED category with at least one business, counted from rows
        # the Overpass API really returned. A DEGRADED capture has no rows and no
        # market block, so it cannot emit a signal.
        out.extend(overpass._signals(rows=rows, columns=columns, market=market))

    elif source_id == "open_meteo":
        # The weather rules read the daily arrays the API returned, not the
        # display strings. The adapter stores them as {"daily": ..., "current":
        # ...}; unwrap to the daily block (and accept a bare daily block too, so
        # an older capture shape still works). No payload (a DEGRADED capture)
        # -> no signal, structurally.
        daily = payload.get("daily") if isinstance(payload, dict) else None
        if daily is None and isinstance(payload, dict) and "time" in payload:
            daily = payload
        out.extend(open_meteo._signals(rows=rows, columns=columns,
                                       daily=daily, source_url=source_url))

    return out


# ---------------------------------------------------------------------------
# The eight probes. Each one makes a real request and reports what came back.
# ---------------------------------------------------------------------------
def probe_marketcheck() -> dict:
    key = os.environ.get("MARKETCHECK_API_KEY", "").strip()
    url = ("https://api.marketcheck.com/v2/search/car/active"
           f"?api_key={key}&car_type=used&zip=14620&radius=25&rows=3")
    code, text = _http(url)
    status = classify(code, text)
    if status == LIVE:
        try:
            payload = json.loads(text)
            listings = payload.get("listings") or []
            total = payload.get("num_found")
            rows = []
            for item in listings[:3]:
                build = item.get("build") or {}
                dealer = (item.get("dealer") or {}).get("website") or "—"
                rows.append([
                    f"{build.get('year','')} {build.get('make','')} {build.get('model','')}".strip(),
                    f"${item.get('price', 0):,}" if item.get("price") else "—",
                    f"{item.get('miles', 0):,} mi" if item.get("miles") else "—",
                    item.get("vin", "—"),
                    str(item.get("dom", "—")),
                    dealer,
                ])
            return _result(
                LIVE,
                f"{total:,} used-car listings within 25 mi of Rochester, NY (14620)" if total else
                f"{len(listings)} listings returned",
                http_code=code,
                rows=rows,
                columns=["Vehicle", "Price", "Mileage", "VIN", "Days on market", "Dealer"],
                source_url="https://www.marketcheck.com/automotive/search?zip=14620&radius=25&car_type=used",
            )
        except (ValueError, KeyError, TypeError) as exc:
            return _result(ERROR, f"HTTP {code} but the body did not parse: {exc}",
                           http_code=code, error=str(exc))
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://www.marketcheck.com/automotive/search?zip=14620&radius=25&car_type=used")


def probe_xweather() -> dict:
    client_id = os.environ.get("XWEATHER_CLIENT_ID", "").strip()
    client_secret = os.environ.get("XWEATHER_CLIENT_SECRET", "").strip()
    url = ("https://data.api.xweather.com/forecast/43.1566,-77.6088"
           f"?client_id={client_id}&client_secret={client_secret}&filter=day&limit=3")
    code, text = _http(url)
    status = classify(code, text)
    if status == LIVE:
        try:
            payload = json.loads(text)
            periods = ((payload.get("response") or [{}])[0].get("periods") or [])[:3]
            rows = [[
                p.get("dateTimeISO", "")[:10],
                p.get("weather", "—"),
                f"{p.get('maxTempF','?')}°F / {p.get('minTempF','?')}°F",
                f"{p.get('precipIN', 0) and round(float(p.get('precipIN', 0)) * 100) or 0}%",
            ] for p in periods]
            return _result(LIVE, f"{len(rows)}-day forecast for Rochester, NY (43.1566,-77.6088)",
                           http_code=code, rows=rows,
                           columns=["Date", "Conditions", "High/Low", "Precip"],
                           source_url="https://www.xweather.com/weather/forecast/rochester-ny")
        except (ValueError, KeyError, TypeError) as exc:
            return _result(ERROR, f"HTTP {code} but the body did not parse: {exc}",
                           http_code=code, error=str(exc))
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://www.xweather.com/weather/forecast/rochester-ny")


def probe_financial_datasets() -> dict:
    key = os.environ.get("FINANCIAL_DATASETS_API_KEY", "").strip()
    url = "https://api.financialdatasets.ai/news/?ticker=AAPL&limit=5"
    code, text = _http(url, headers={"X-API-KEY": key} if key else None)
    status = classify(code, text)
    if status == LIVE:
        try:
            payload = json.loads(text)
            items = (payload.get("news") or payload.get("articles") or [])[:5]
            rows = [[i.get("title", "—"), i.get("source", "—"), (i.get("date") or "")[:10]] for i in items]
            return _result(LIVE, f"{len(rows)} headlines returned", http_code=code, rows=rows,
                           columns=["Headline", "Source", "Date"],
                           source_url="https://financialdatasets.ai/news")
        except (ValueError, KeyError, TypeError) as exc:
            return _result(ERROR, f"HTTP {code} but the body did not parse: {exc}",
                           http_code=code, error=str(exc))
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://financialdatasets.ai/news")


def probe_massive() -> dict:
    key = os.environ.get("MASSIVE_API_KEY", "").strip()
    url = "https://api.massive.com/v2/aggs/ticker/AAPL/prev"
    code, text = _http(url, headers={"Authorization": f"Bearer {key}"} if key else None)
    status = classify(code, text)
    if status == NOT_ENTITLED:
        # The plan, not the credential, is the blocker. Say exactly that.
        return _result(NOT_ENTITLED, MASSIVE_NOT_ENTITLED_REASON, http_code=code,
                       source_url="https://api.massive.com/v2/aggs/ticker/AAPL/prev")
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://api.massive.com/v2/aggs/ticker/AAPL/prev")


#: The mapbox adapter has five of its own statuses; the registry has four slots.
#: RATE LIMITED and DEGRADED both surface as ERROR, and the evidence line keeps
#: the adapter's literal wording so the difference is never hidden.
MAPBOX_LIVE_STATUS = {
    mapbox_source.OK: LIVE,
    mapbox_source.NEEDS_KEY: NEEDS_KEY,
    mapbox_source.NOT_ENTITLED: NOT_ENTITLED,
    mapbox_source.RATE_LIMITED: ERROR,
    mapbox_source.DEGRADED: ERROR,
}


def probe_mapbox() -> dict:
    """Countable market sizing from the Mapbox Search Box adapter.

    Six categories, one real count each, inside 50 mi of Rochester, NY. No token
    -> NEEDS KEY with zero rows, zero signals and no request sent at all; every
    non-200 -> the same zero-row shape. The token is read by ``mapbox_source``
    (environment first, then the secrets vault) and never reaches this module's
    strings.
    """
    result = mapbox_source.count_market(
        mapbox_source.CATEGORIES,
        mapbox_source.DEFAULT_LAT,
        mapbox_source.DEFAULT_LON,
        mapbox_source.DEFAULT_RADIUS_MILES,
    )
    status = MAPBOX_LIVE_STATUS.get(result.get("status"), ERROR)
    detail = str(result.get("reason") or "")
    if result.get("status") == mapbox_source.RATE_LIMITED:
        detail = f"RATE LIMITED — {detail}"
    return _result(
        status,
        detail,
        http_code=result.get("http_code"),
        rows=result.get("rows") or [],
        columns=result.get("columns") or [],
        source_url=result.get("source_url") or mapbox_source.SOURCE_URL,
        error=result.get("error") or "",
        market=result.get("market"),
    )


#: The keyless adapters have two statuses; a DEGRADED result stays DEGRADED so the
#: page and the ingest bridge both say "NOT CONVERTED" instead of smoothing a
#: failed call into a zero.
KEYLESS_LIVE_STATUS = {
    overpass.OK: LIVE,
    overpass.DEGRADED: DEGRADED,
}


def probe_overpass() -> dict:
    """Countable market sizing from OpenStreetMap — no key, no signup.

    One SMALL Overpass QL request per trade (six), each failed over across the
    public mirrors on 429/500/502/503/504 or a timeout and each cached briefly,
    deduped by OSM id across categories. Partial failure is reported as such: the
    categories that answered carry real counts, the rest carry ``count: None``
    with their literal reason. Only an all-fail run comes back DEGRADED, with the
    literal reason and zero rows: nothing is fabricated to fill the card.
    """
    result = overpass.snapshot(
        overpass.DEFAULT_LAT, overpass.DEFAULT_LON, overpass.DEFAULT_RADIUS_MILES,
    )
    status = KEYLESS_LIVE_STATUS.get(result.get("status"), DEGRADED)
    return _result(
        status,
        str(result.get("reason") or ""),
        http_code=result.get("http_code"),
        rows=result.get("rows") or [],
        columns=result.get("columns") or [],
        source_url=result.get("source_url") or overpass.SOURCE_URL,
        error=result.get("error") or "",
        market=result.get("market"),
    )


def probe_open_meteo() -> dict:
    """Current conditions + 7-day forecast from Open-Meteo — no key, no signup.

    The request URL itself is the cited ``source_url`` (the Open-Meteo call that
    produced every number), and the daily arrays ride along in ``payload`` so the
    signal rules read figures, not formatted strings.
    """
    result = open_meteo.snapshot(open_meteo.DEFAULT_LAT, open_meteo.DEFAULT_LON,
                                 days=open_meteo.DEFAULT_DAYS)
    status = KEYLESS_LIVE_STATUS.get(result.get("status"), DEGRADED)
    return _result(
        status,
        str(result.get("reason") or ""),
        http_code=result.get("http_code"),
        rows=result.get("rows") or [],
        columns=result.get("columns") or [],
        source_url=result.get("source_url") or open_meteo.ENDPOINT,
        error=result.get("error") or "",
        payload=result.get("payload") or None,
    )


def probe_rentcast() -> dict:
    key = os.environ.get("RENTCAST_API_KEY", "").strip()
    url = "https://api.rentcast.io/v1/listings/sale?city=Rochester&state=NY&limit=3"
    code, text = _http(url, headers={"X-Api-Key": key} if key else None)
    status = classify(code, text)
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://developers.rentcast.io/reference/introduction")


def probe_interfaze() -> dict:
    key = os.environ.get("INTERFAZE_API_KEY", "").strip()
    url = "https://api.interfaze.ai/v1/chat/completions"
    body = json.dumps({"model": "interfaze-beta", "messages": [{"role": "user", "content": "ping"}]}).encode()
    code, text = _http(url, method="POST", body=body,
                       headers={"Content-Type": "application/json",
                                **({"Authorization": f"Bearer {key}"} if key else {})})
    status = classify(code, text)
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://docs.interfaze.ai/")


def probe_parallel() -> dict:
    key = os.environ.get("PARALLEL_API_KEY", "").strip()
    url = "https://api.parallel.ai/v1beta/search"
    body = json.dumps({"objective": "Rochester NY HVAC contractor demand", "max_results": 3}).encode()
    code, text = _http(url, method="POST", body=body,
                       headers={"Content-Type": "application/json",
                                **({"x-api-key": key} if key else {})})
    status = classify(code, text)
    return _result(status, f"HTTP {code}: {_snippet(text)}", http_code=code,
                   source_url="https://docs.parallel.ai/")


#: The Groq adapter has two statuses; a DEGRADED result (missing key, 429, 401,
#: timeout) stays DEGRADED so the page and the ingest bridge both say
#: "NOT CONVERTED" instead of smoothing a failed call into generated text.
GROQ_LIVE_STATUS = {
    groq_source.OK: LIVE,
    groq_source.DEGRADED: DEGRADED,
}


def probe_groq() -> dict:
    """Health check for the Groq adapter: one real ``GET /openai/v1/models``.

    The credential is read by ``groq_source`` (environment first, then the
    secrets vault) and never reaches this module's strings. A 200 is LIVE with
    the model inventory as rows; every other outcome keeps its literal status
    (``http_code``) and its literal reason, with zero rows — an LLM draft is not
    a measurement, so this source emits no signals and therefore zero claims.
    """
    result = groq_source.probe()
    status = GROQ_LIVE_STATUS.get(result.get("status"), DEGRADED)
    return _result(
        status,
        str(result.get("reason") or ""),
        http_code=result.get("http_code"),
        rows=result.get("rows") or [],
        columns=result.get("columns") or [],
        source_url=result.get("source_url") or groq_source.SOURCE_URL,
        error=result.get("error") or "",
        payload=result.get("payload") or None,
    )


#: The Tavily adapter has two statuses; a DEGRADED result (missing key, 429 after
#: the retries are exhausted, 401, timeout) stays DEGRADED so the page and the
#: ingest bridge both say "NOT CONVERTED" instead of smoothing a failed call into
#: an empty result list.
TAVILY_LIVE_STATUS = {
    tavily_source.OK: LIVE,
    tavily_source.DEGRADED: DEGRADED,
}


def probe_tavily() -> dict:
    """One real authenticated ``POST https://api.tavily.com/search``.

    The credential is read by ``tavily_source`` (environment first, then the
    secrets vault, where it is stored as ``tavily``) and never reaches this
    module's strings. A 200 is LIVE with one row per result — title, URL, score
    and a snippet — plus the real result count in ``payload``; every other
    outcome keeps its literal status (``http_code``) and its literal reason, with
    zero rows. A search hit is a pointer, not a measurement, so this source emits
    no signal and therefore zero claims.
    """
    result = tavily_source.probe()
    status = TAVILY_LIVE_STATUS.get(result.get("status"), DEGRADED)
    return _result(
        status,
        str(result.get("reason") or ""),
        http_code=result.get("http_code"),
        rows=result.get("rows") or [],
        columns=result.get("columns") or [],
        source_url=result.get("source_url") or tavily_source.SOURCE_URL,
        error=result.get("error") or "",
        payload=result.get("payload") or None,
        result_count=result.get("result_count"),
    )


# ---------------------------------------------------------------------------
# The registry
# ---------------------------------------------------------------------------
SOURCES = [
    {
        "id": "marketcheck",
        "name": "Marketcheck",
        "feeds": "Local market opportunity detection",
        "feeds_detail": "Used-car inventory, price and days-on-market for a radius around Rochester, NY.",
        "credential_env": "MARKETCHECK_API_KEY",
        "probe": probe_marketcheck,
        "docs": "https://www.marketcheck.com/automotive/search?zip=14620&radius=25&car_type=used",
    },
    {
        "id": "xweather",
        "name": "Xweather",
        "feeds": "Weather-triggered service demand (HVAC, roofing, landscaping)",
        "feeds_detail": "3-day forecast drives the demand model: a mild stretch suppresses HVAC calls, a dry sunny stretch suppresses roofing.",
        "credential_env": "XWEATHER_CLIENT_ID + XWEATHER_CLIENT_SECRET",
        "probe": probe_xweather,
        "docs": "https://www.xweather.com/weather/forecast/rochester-ny",
    },
    {
        "id": "financial_datasets",
        "name": "Financial Datasets",
        "feeds": "Trend detection and sector movement",
        "feeds_detail": "Headline flow and sector prints that become trend signals for the opportunity engine.",
        "credential_env": "FINANCIAL_DATASETS_API_KEY",
        "probe": probe_financial_datasets,
        "docs": "https://financialdatasets.ai/news",
    },
    {
        "id": "massive",
        "name": "Massive",
        "feeds": "Ticker-level price evidence for verification",
        "feeds_detail": "Aggregates used to check a price claim before it is allowed to become a verified opportunity.",
        "credential_env": "MASSIVE_API_KEY",
        "probe": probe_massive,
        "docs": "https://api.massive.com/v2/aggs/ticker/AAPL/prev",
    },
    {
        "id": "mapbox",
        "name": "Mapbox",
        "feeds": "Countable local market sizing",
        "feeds_detail": ("Six trades counted inside 50 mi of Rochester, NY — HVAC contractor, plumber, "
                         "landscaper, dentist, roofing contractor, electrician — one real count per "
                         "category, so a market can be counted instead of guessed."),
        "credential_env": "MAPBOX_TOKEN",
        "probe": probe_mapbox,
        "docs": mapbox_source.SOURCE_URL,
    },
    {
        "id": "overpass",
        "name": "Overpass (OpenStreetMap)",
        "feeds": "Countable local market sizing — keyless",
        "feeds_detail": ("Six trades counted inside 50 mi of Rochester, NY from OpenStreetMap with no key "
                         "and no signup — HVAC contractor, plumber, landscaper, dentist, roofer, "
                         "electrician. One small Overpass QL query per trade, failed over in order across "
                         "four public mirrors (overpass-api.de → kumi.systems → private.coffee → "
                         "maps.mail.ru) on 502/503/504/timeout, cached in-process for 15 minutes, "
                         "de-duplicated by OSM id, so the market is counted instead of guessed."),
        "credential_env": "",
        "keyless": True,
        "probe": probe_overpass,
        "docs": overpass.SOURCE_URL,
        "scope": overpass.scope_line(),
    },
    {
        "id": "open_meteo",
        "name": "Open-Meteo",
        "feeds": "Weather-triggered service demand — keyless",
        "feeds_detail": ("Current conditions plus a 7-day forecast (high/low temperature, precipitation, "
                         "max wind) for Rochester, NY. Free and keyless, so the demand model keeps a real "
                         "forecast even when no weather credential is configured."),
        "credential_env": "",
        "keyless": True,
        "probe": probe_open_meteo,
        "docs": open_meteo.ENDPOINT,
        "scope": f"{open_meteo.DEFAULT_LABEL} · {open_meteo.DEFAULT_DAYS}-day forecast",
    },
    {
        "id": "rentcast",
        "name": "RentCast",
        "feeds": "Real-estate market signals",
        "feeds_detail": "Sale and rental listings, price history and days-on-market for the property side of the loop.",
        "credential_env": "RENTCAST_API_KEY",
        "probe": probe_rentcast,
        "docs": "https://developers.rentcast.io/reference/introduction",
    },
    {
        "id": "interfaze",
        "name": "Interfaze",
        "feeds": "OCR, speech-to-text, object detection for document/image ingestion",
        "feeds_detail": "Turns a photographed invoice, a scanned flyer or a call recording into structured text the loop can read.",
        "credential_env": "INTERFAZE_API_KEY",
        "probe": probe_interfaze,
        "docs": "https://docs.interfaze.ai/",
    },
    {
        "id": "parallel",
        "name": "Parallel Search",
        "feeds": "Research-grade web search for opportunity sourcing",
        "feeds_detail": "Long-tail research queries that surface opportunities no feed carries.",
        "credential_env": "PARALLEL_API_KEY",
        "probe": probe_parallel,
        "docs": "https://docs.parallel.ai/",
    },
    {
        "id": "groq",
        "name": "Groq",
        "feeds": "Generated drafts — the loop's writing step",
        "feeds_detail": ("Hosted open-model generation through the vault-gated Groq adapter: the health "
                         "check lists the models the stored GROQ_API_KEY can actually see, and a draft is "
                         "reported as generated text with its model and token usage — never converted into "
                         "a claim, because a sentence is not a measurement."),
        "credential_env": groq_source.TOKEN_NAME,
        "probe": probe_groq,
        "docs": groq_source.SOURCE_URL,
        "scope": f"{groq_source.MODEL} · {groq_source.MODELS_ENDPOINT}",
    },
    {
        "id": "tavily",
        "name": "Tavily",
        "feeds": "Live web research — what the market is saying right now",
        "feeds_detail": ("Real web search through the vault-gated Tavily adapter: one authenticated "
                         "POST /search returns ranked pages with their titles, URLs and snippets "
                         "for a live local-market query, so a signal can always be traced to the "
                         "page it came from. A search hit is a pointer, not a measurement, so this "
                         "source emits no signal and writes zero claims."),
        "credential_env": tavily_source.TOKEN_NAME,
        "probe": probe_tavily,
        "docs": tavily_source.SOURCE_URL,
        "scope": (f"{tavily_source.MAX_RESULTS} results · search_depth="
                  f"{tavily_source.SEARCH_DEPTH} · POST {tavily_source.ENDPOINT}"),
    },
]

SOURCE_BY_ID = {s["id"]: s for s in SOURCES}


# ---------------------------------------------------------------------------
# Seeded captures — REAL data captured 2026-11-18, each row citing its source.
# ---------------------------------------------------------------------------
SEED_CAPTURES = [
    {
        "source_id": "marketcheck",
        "captured_at": "2026-11-18T06:12:00Z",
        "status": LIVE,
        "http_code": 200,
        "detail": "3,955 used-car listings within 25 mi of Rochester, NY (14620)",
        "source_url": "https://www.marketcheck.com/automotive/search?zip=14620&radius=25&car_type=used",
        "columns": ["Vehicle", "Price", "Mileage", "VIN", "Days on market", "Dealer"],
        "rows": [
            ["2015 JEEP WRANGLER", "$16,424", "119,000 mi", "1C4HJWEG5FL740904", "14",
             "greenlightautosalesny.mycarsonline.com"],
            ["2016 CHEVROLET SILVERADO 1500 DOUBLE CAB", "$17,924", "91,500 mi", "1GCVKRECXGZ353116", "152", "—"],
            ["2012 HONDA PILOT", "$10,500", "121,000 mi", "5FNYF4H92CB082024", "22", "—"],
        ],
        "note": ("The Silverado at 152 days on market is a stale-inventory signal — exactly the kind of "
                 "trigger the opportunity engine should act on."),
    },
    {
        "source_id": "xweather",
        "captured_at": "2026-11-18T06:14:00Z",
        "status": LIVE,
        "http_code": 200,
        "detail": "3-day forecast for Rochester, NY (43.1566,-77.6088)",
        "source_url": "https://www.xweather.com/weather/forecast/rochester-ny",
        "columns": ["Date", "Conditions", "High/Low", "Precip"],
        "rows": [
            ["Nov 18", "Mostly Sunny", "57°F / 38°F", "0%"],
            ["Nov 19", "Partly Cloudy", "62°F / 46°F", "0%"],
            ["Nov 20", "Sunny", "60°F / 39°F", "0%"],
        ],
        "note": ("Three dry, mild days: no storm-driven roofing or restoration demand, and a 62°F Thursday "
                 "suppresses heating calls. That is a demand dip an HVAC contractor should be told about before it lands."),
    },
    {
        "source_id": "financial_datasets",
        "captured_at": "2026-11-18T06:18:00Z",
        "status": LIVE,
        "http_code": 200,
        "detail": "5 headlines returned",
        "source_url": "https://financialdatasets.ai/news",
        "columns": ["Headline", "Source", "Date"],
        "rows": [
            ["Treasuries Edge Higher for a Third Day as Risk Appetite Falters", "Bloomberg", "2026-11-18"],
            ["Fidelity Says Even at 6% Treasuries Fail to Be 'Massively Cheap'", "Bloomberg", "2026-11-18"],
            ["US tightens AI chip controls, probes Megaspeed", "The American Bazaar", "2026-11-17"],
            ["AECOM stock trades up, here is why", "TradingView", "2026-11-17"],
            ["Homebuilder confidence sinks to a 14-year low as buyers hibernate", "HousingWire", "2026-11-17"],
        ],
        "note": ("The homebuilder-confidence story is a real trend signal worth an opportunity: a 14-year low in "
                 "builder confidence means builders are cutting marketing spend exactly when they need buyers."),
    },
    {
        "source_id": "massive",
        "captured_at": "2026-11-18T06:20:00Z",
        "status": NOT_ENTITLED,
        "http_code": 403,
        "detail": "HTTP 403: not entitled to this data — plan upgrade required",
        "source_url": "https://api.massive.com/v2/aggs/ticker/AAPL/prev",
        "columns": [],
        "rows": [],
        "note": ("Price claims cannot be verified through this source until the plan is upgraded. The verification "
                 "layer must treat ticker-level price evidence as UNAVAILABLE, not as passing."),
    },
    {
        "source_id": "mapbox",
        "captured_at": "2026-11-18T06:22:00Z",
        "status": NEEDS_KEY,
        "http_code": 401,
        "detail": "HTTP 401: Not Authorized - No Token",
        "source_url": mapbox_source.SOURCE_URL,
        "columns": [],
        "rows": [],
        "note": "Coded and ready. Set MAPBOX_TOKEN (environment or the secrets vault) to turn this into a countable market size.",
    },
    {
        "source_id": "rentcast",
        "captured_at": "2026-11-18T06:22:00Z",
        "status": NEEDS_KEY,
        "http_code": 401,
        "detail": "HTTP 401: No API key provided in request. An API key must be provided in the 'X-Api-Key' header",
        "source_url": "https://developers.rentcast.io/reference/introduction",
        "columns": [],
        "rows": [],
        "note": "Coded and ready. Set RENTCAST_API_KEY to turn this on.",
    },
    {
        "source_id": "interfaze",
        "captured_at": "2026-11-18T06:23:00Z",
        "status": NEEDS_KEY,
        "http_code": 401,
        "detail": "HTTP 401: credential required",
        "source_url": "https://docs.interfaze.ai/",
        "columns": [],
        "rows": [],
        "note": "Coded and ready. Set INTERFAZE_API_KEY to turn this on.",
    },
    {
        "source_id": "parallel",
        "captured_at": "2026-11-18T06:23:00Z",
        "status": NEEDS_KEY,
        "http_code": 401,
        "detail": "HTTP 401: No API key provided (C.0)",
        "source_url": "https://docs.parallel.ai/",
        "columns": [],
        "rows": [],
        "note": "Coded and ready. Set PARALLEL_API_KEY to turn this on.",
    },
]


# ---------------------------------------------------------------------------
# In-memory state: the capture log (newest first) and the latest result per source
# ---------------------------------------------------------------------------
_LOCK = threading.RLock()
_CAPTURES: list[dict] = []
_LATEST: dict[str, dict] = {}
_SEEDED = False


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


def _record_capture(entry: dict) -> dict:
    """Append one capture to the log and make it the source's current status."""
    with _LOCK:
        _CAPTURES.insert(0, entry)
        del _CAPTURES[CAPTURE_LOG_LIMIT:]
        _LATEST[entry["source_id"]] = entry
    return entry


def seed_if_empty() -> int:
    """Load the 2026-11-18 captures once, and put their provenance in the audit chain."""
    global _SEEDED
    with _LOCK:
        if _SEEDED or _CAPTURES:
            _SEEDED = True
            return 0
        for capture in reversed(SEED_CAPTURES):
            entry = dict(capture)
            entry["seeded"] = True
            entry["trigger"] = "seed"
            entry["error"] = ""
            _record_capture(entry)
        _SEEDED = True
    # Provenance goes into the hash chain, once per process start.
    for capture in SEED_CAPTURES:
        try:
            audit.record(
                actor=COMPONENT_NAME,
                action="live_data.capture.seeded",
                subject_type="source",
                subject_id=capture["source_id"],
                payload={
                    "captured_at": capture["captured_at"],
                    "status": capture["status"],
                    "http_code": capture["http_code"],
                    "detail": capture["detail"],
                    "source_url": capture["source_url"],
                    "rows": len(capture["rows"]),
                    "capture_date": CAPTURE_DATE,
                },
            )
        except Exception as exc:  # pragma: no cover - never block startup
            log.warning("audit write failed for seeded capture %s: %s", capture["source_id"], exc)
    return len(SEED_CAPTURES)


def probe_never_probed(only: tuple[str, ...] | None = None) -> list[dict]:
    """Probe, for real, every source that has no recorded capture yet.

    A source that has never been checked has no honest badge to show, so it is
    checked: one real HTTP call per source through ``_probe_one`` (which turns a
    crash into an ERROR, never a pass) and the literal outcome is recorded with
    the trigger ``first-probe``. Nothing here sets a status by hand — that is
    why this is safe to run on startup.

    Each probe runs in a small thread pool and its result is recorded the moment
    IT finishes, so one slow adapter (Overpass fails over across four mirrors and
    can take a minute) never holds up the fast ones. ``only`` restricts the sweep
    to those ids. Returns the entries that were recorded, in completion order.
    """
    seed_if_empty()
    with _LOCK:
        pending = [s for s in SOURCES if s["id"] not in _LATEST]
    if only is not None:
        allowed = set(only)
        pending = [s for s in pending if s["id"] in allowed]
    if not pending:
        return []

    recorded: list[dict] = []
    with ThreadPoolExecutor(max_workers=8) as pool:
        futures = {pool.submit(_probe_one, source): source for source in pending}
        for future in as_completed(futures):
            source = futures[future]
            try:
                entry = future.result()
            except Exception as exc:  # pragma: no cover - _probe_one never raises
                entry = _result(ERROR, f"{type(exc).__name__}: {exc}",
                                error=str(exc), source_url=source["docs"])
                entry = {
                    "source_id": source["id"], "captured_at": _now_iso(),
                    "status": entry["status"], "http_code": entry.get("http_code"),
                    "detail": entry.get("detail", ""), "source_url": source["docs"],
                    "columns": [], "rows": [], "error": entry.get("error", ""),
                    "market": None, "payload": None, "result_count": 0,
                    "seeded": False, "trigger": "first-probe",
                }
            entry["trigger"] = "first-probe"
            _record_capture(entry)
            recorded.append(entry)
            log.info("live data: first-probe %s -> %s (%s)",
                     entry["source_id"], entry["status"], entry.get("http_code") or "no HTTP")
            try:
                audit.record(
                    actor=COMPONENT_NAME,
                    action="live_data.probe",
                    subject_type="source",
                    subject_id=entry["source_id"],
                    payload={
                        "status": entry["status"],
                        "http_code": entry["http_code"],
                        "detail": entry["detail"],
                        "source_url": entry["source_url"],
                        "rows": len(entry["rows"]),
                        "result_count": entry.get("result_count"),
                        "trigger": "first-probe",
                    },
                )
            except Exception as exc:  # pragma: no cover - never block a page load
                log.warning("audit write failed for first probe %s: %s",
                            entry["source_id"], exc)
    return recorded


def warm_in_background(only: tuple[str, ...] | None = None) -> threading.Thread:
    """Run ``probe_never_probed()`` on a daemon thread so startup never waits.

    The server starts listening immediately; the sources that had no capture get
    their real status a few seconds later. A failure in the sweep can never take
    the process down.
    """
    def _run():
        try:
            entries = probe_never_probed(only=only)
            if entries:
                log.info("live data: first-probed %d source(s): %s", len(entries),
                         ", ".join(f"{e['source_id']}={e['status']}" for e in entries))
        except Exception as exc:  # pragma: no cover - a warm must never crash
            log.warning("live data first-probe sweep failed: %s", exc)

    thread = threading.Thread(target=_run, name="live-data-first-probe", daemon=True)
    thread.start()
    return thread


def _probe_one(source: dict) -> dict:
    """Run one adapter's probe. A crash is an ERROR, never a pass."""
    try:
        result = source["probe"]()
    except Exception as exc:  # network down, DNS, timeout, anything
        result = _result(ERROR, f"{type(exc).__name__}: {exc}", error=str(exc),
                         source_url=source["docs"])
    entry = {
        "source_id": source["id"],
        "captured_at": _now_iso(),
        "status": result["status"],
        "http_code": result.get("http_code"),
        "detail": result.get("detail", ""),
        "source_url": result.get("source_url") or source["docs"],
        "columns": result.get("columns") or [],
        "rows": result.get("rows") or [],
        "error": result.get("error", ""),
        "market": result.get("market"),
        # The structured payload behind the rows (open_meteo's daily arrays).
        # Without it the weather rules would have to re-parse display strings.
        "payload": result.get("payload"),
        # The real number of results the endpoint returned (Tavily: the
        # search hits). ``None`` when the adapter does not report one, so the
        # UI can say "not reported" instead of inventing a 0.
        "result_count": result.get("result_count"),
        "seeded": False,
        "trigger": "probe",
    }
    return entry


def probe_all(trigger: str = "ui", write_audit: bool = True) -> dict:
    """Re-run every adapter for real, append the results, and audit each one."""
    seed_if_empty()
    started = _now_iso()
    with ThreadPoolExecutor(max_workers=8) as pool:
        entries = list(pool.map(_probe_one, SOURCES))
    for entry in entries:
        _record_capture(entry)
        if write_audit:
            try:
                audit.record(
                    actor=COMPONENT_NAME,
                    action="live_data.probe",
                    subject_type="source",
                    subject_id=entry["source_id"],
                    payload={
                        "status": entry["status"],
                        "http_code": entry["http_code"],
                        "detail": entry["detail"],
                        "source_url": entry["source_url"],
                        "rows": len(entry["rows"]),
                        "trigger": trigger,
                    },
                )
            except Exception as exc:  # pragma: no cover - defensive
                log.warning("audit write failed for probe %s: %s", entry["source_id"], exc)
    summary = summarize(entries)
    if write_audit:
        try:
            audit.record(
                actor=COMPONENT_NAME,
                action="live_data.probe_run",
                subject_type="probe_run",
                subject_id=started,
                payload={"trigger": trigger, "started_at": started, "finished_at": _now_iso(),
                         "counts": summary["counts"], "total": summary["total"]},
            )
        except Exception as exc:  # pragma: no cover - defensive
            log.warning("audit write failed for probe run: %s", exc)
    return {"started_at": started, "finished_at": _now_iso(), "results": entries, "summary": summary}


def summarize(entries: list[dict] | None = None) -> dict:
    """Count the statuses. Derived from the entries, never from a constant."""
    if entries is None:
        entries = list(_LATEST.values())
    counts = {status: 0 for status in STATUS_ORDER}
    for entry in entries:
        counts[entry["status"]] = counts.get(entry["status"], 0) + 1
    return {
        "counts": counts,
        "total": len(entries),
        "live": counts.get(LIVE, 0),
        "needs_key": counts.get(NEEDS_KEY, 0),
        "not_entitled": counts.get(NOT_ENTITLED, 0),
        "error": counts.get(ERROR, 0),
        "line": (f"{counts.get(LIVE,0)} of {len(entries)} sources live · "
                 f"{counts.get(NEEDS_KEY,0)} need keys · "
                 f"{counts.get(NOT_ENTITLED,0)} not entitled"),
    }


def cards() -> list[dict]:
    """The adapter cards, each carrying its current status and its evidence.

    With ``probe_never_probed=True`` — the default for ``snapshot()``, which is
    what the page and ``GET /api/live-data`` serve — any source that has no
    recorded capture yet is probed for real, once, instead of being rendered as
    an ``ERROR`` / "never probed" placeholder. That is what makes a freshly
    restartable process show a truthful LIVE badge for a source it has never
    checked, without a hand-set status: the badge is still the outcome of a real
    HTTP call.
    """
    seed_if_empty()
    out = []
    for source in SOURCES:
        latest = _LATEST.get(source["id"])
        # The most recent capture that actually returned data, for provenance.
        last_live = next((c for c in _CAPTURES
                          if c["source_id"] == source["id"] and c["status"] == LIVE), None)
        out.append({
            "id": source["id"],
            "name": source["name"],
            "feeds": source["feeds"],
            "feeds_detail": source["feeds_detail"],
            "credential_env": source["credential_env"],
            "docs": source["docs"],
            "status": latest["status"] if latest else ERROR,
            "detail": latest["detail"] if latest else "never probed",
            "http_code": latest["http_code"] if latest else None,
            "captured_at": latest["captured_at"] if latest else None,
            "source_url": latest["source_url"] if latest else source["docs"],
            "columns": latest["columns"] if latest else [],
            "rows": latest["rows"] if latest else [],
            "result_count": (latest.get("result_count")
                             if latest and latest.get("result_count") is not None
                             else (len(latest["rows"]) if latest else 0)),
            "query": ((latest.get("payload") or {}).get("query") if latest else "") or "",
            "note": latest.get("note", "") if latest else "",
            "market": latest.get("market") if latest else None,
            # The scope every number on this card is stated against (the
            # countable-market line for overpass, the forecast window for
            # open_meteo). Empty for the adapters that do not declare one.
            "scope": source.get("scope", ""),
            "keyless": bool(source.get("keyless")),
            "signals": _signals(
                source["id"],
                latest["rows"] if latest else [],
                latest["columns"] if latest else [],
                latest.get("market") if latest else None,
                latest.get("payload") if latest else None,
                latest["source_url"] if latest else source["docs"],
            ),
            "seeded": bool(latest.get("seeded")) if latest else False,
            "last_live_at": last_live["captured_at"] if last_live else None,
            "last_live_rows": len(last_live["rows"]) if last_live else 0,
            # The full payload of the most recent capture that actually returned
            # data. Kept so a later failed probe never erases real evidence: the
            # badge tells the truth about *now*, this block shows what we really
            # captured and when.
            "last_live": ({
                "captured_at": last_live["captured_at"],
                "columns": last_live.get("columns") or [],
                "rows": last_live.get("rows") or [],
                "detail": last_live.get("detail", ""),
                "source_url": last_live.get("source_url", ""),
                "seeded": bool(last_live.get("seeded")),
            } if last_live and last_live.get("rows") else None),
        })
    return out


def capture_log(limit: int = 40) -> list[dict]:
    seed_if_empty()
    with _LOCK:
        return [dict(entry) for entry in _CAPTURES[:limit]]


def snapshot() -> dict:
    """Everything the page and the JSON API need, in one call.

    Read-only: it reports the most recent recorded capture for each source and
    starts nothing. ``probe_never_probed()`` is the explicit "go and check the
    sources nobody has checked yet" call, used at startup and by the JSON API
    when asked.
    """
    seed_if_empty()
    return {
        "capture_date": CAPTURE_DATE,
        "sources": cards(),
        "summary": summarize(),
        "log": capture_log(limit=40),
        "generated_at": _now_iso(),
        "stale_dom_days": STALE_DOM_DAYS,
        "signals": [sig for card in cards() for sig in card.get("signals", [])],
    }


def reset_for_tests() -> None:
    """Test hook: forget in-memory state so a test starts from the seeded captures."""
    global _SEEDED
    with _LOCK:
        _CAPTURES.clear()
        _LATEST.clear()
        _SEEDED = False
