"""THE LIVE-DATA -> OPPORTUNITY BRIDGE — signals in, cited claims out.

Why this file exists
--------------------
``live_data.py`` already reads eight real adapters and derives named signals
(STALE INVENTORY / DEMAND DIP / TREND) from the rows each one really returned.
``opportunity.py`` already scores a cluster of real stored signals and refuses
to store anything it cannot cite. What was missing was the wire between them:
nothing ever turned a live signal into a *claim*.

This module is that wire, and nothing more. For each source in
``live_data.snapshot()``:

    1. the emitted signal is written into the operational ``signals`` table
       through ``ingestion._insert_signal`` (the only signal write path), so the
       evidence behind a claim is a real, inspectable row with a stable id;
    2. the signals are grouped by kind and turned into an opportunity candidate
       by ``opportunity.build_opportunity`` — the documented scoring rules and
       the hard "no citation, no opportunity" gate are NOT re-implemented here;
    3. each signal's own sentence (``signal["line"]``) becomes one claim, written
       through ``memory.create_claim`` — the only write path into ``claims``,
       which refuses any claim without both a ``source_url`` and a
       ``source_turn``.

HARD RULE — A FAILED SOURCE WRITES NOTHING
------------------------------------------
A source that answered 401, 403 or 402 refused us. Its status is recorded as
``DEGRADED`` with the *literal* reason the endpoint gave (never paraphrased) and
it writes ZERO claims. A stale capture from this morning is never re-labelled as
a fresh claim: if the source is degraded now, the bridge reports zero signals
and zero claims, even if yesterday's rows are still in the log. Nothing is
fabricated to make the strip look good.

What the caller gets back
-------------------------
``ingest_live_signals(conn, sources=None)`` returns

    {source_id: {status, signals, claims_written, ...}}

where ``status`` is one of ``OK`` (LIVE and converted), ``DEGRADED`` (401/402/403
— literal reason recorded, zero claims) or ``ERROR`` (network failure or a body
that did not parse — also zero claims). ``conn`` is the operational SQLite
connection (``orchestrator.db.connect()``); it is used to store the signals.
"""

from __future__ import annotations

import logging
import re
from datetime import datetime, timezone

from . import ingestion
from . import live_data
from . import memory
from . import opportunity

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

COMPONENT_NAME = "LiveIngestBridge"

#: A LIVE source whose signals were converted.
STATUS_OK = "OK"
#: The endpoint refused us (401/402/403). Literal reason kept, zero claims.
STATUS_DEGRADED = "DEGRADED"
#: Network failure / unparseable body. Also zero claims.
STATUS_ERROR = "ERROR"

#: The HTTP codes that mean "this source said no". Never turned into a claim.
DEGRADED_HTTP_CODES = (401, 402, 403)

#: ``live_data`` statuses that mean the same thing. ``DEGRADED`` is the keyless
#: adapters' own status (overpass / open_meteo answered with an error, a rate
#: limit or a timeout): the literal reason is kept and zero claims are written,
#: exactly like a 401 from a keyed source.
DEGRADED_STATUSES = (live_data.NEEDS_KEY, live_data.NOT_ENTITLED, live_data.DEGRADED)

#: Prefix on the ``signals.source`` column so live-derived rows are identifiable.
SIGNAL_SOURCE_PREFIX = "live_data/"

#: Every adapter this bridge converts, derived from the registry itself so a new
#: source cannot be forgotten. ``mapbox`` is one of them: when it is LIVE its
#: MARKET SIZE signal becomes one cited claim through the same path as the rest,
#: and a NEEDS KEY / NOT ENTITLED / RATE LIMITED mapbox writes ZERO claims —
#: structurally, because a refused card has no rows and no signals to convert.
BRIDGED_SOURCE_IDS = tuple(source["id"] for source in live_data.SOURCES)

#: The last ingest result, kept in memory for the Live Data page strip.
_LAST: dict | None = None


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


def _slug(text: str) -> str:
    out = re.sub(r"[^a-z0-9]+", "-", str(text or "").lower()).strip("-")
    return out or "signal"


def _refusal(card: dict) -> tuple[bool, int | None]:
    """Is this source refusing us? Returns (refused, http_code)."""
    code = card.get("http_code")
    if code in DEGRADED_HTTP_CODES:
        return True, code
    if card.get("status") in DEGRADED_STATUSES:
        return True, code
    return False, code


def _literal_reason(card: dict) -> str:
    """The reason the endpoint actually gave — verbatim, never rewritten."""
    detail = str(card.get("detail") or "").strip()
    if detail:
        return detail
    code = card.get("http_code")
    return f"HTTP {code}: source refused the request" if code else "source refused the request"


def _entry(card: dict, status: str, *, signals: int, claims_written: int,
           reason: str = "", claims_skipped: int = 0,
           opportunities: list[str] | None = None, stored_signals: int = 0) -> dict:
    market = card.get("market") if isinstance(card.get("market"), dict) else {}
    return {
        "name": card.get("name", card.get("id", "")),
        "status": status,
        "signals": signals,
        "claims_written": claims_written,
        "claims_skipped": claims_skipped,
        "stored_signals": stored_signals,
        "opportunities": list(opportunities or []),
        "reason": reason,
        "http_code": card.get("http_code"),
        "captured_at": card.get("captured_at"),
        "source_url": card.get("source_url", ""),
        # Provenance rides along per source: which mirror actually served the
        # bytes (empty when nothing answered) and how the fetch was transported.
        "mirror": market.get("mirror") or card.get("mirror") or "",
        "served_by": market.get("served_by") or "",
        "transport": market.get("transport") or "",
        "cached": bool(market.get("cached_any")),
    }


# ---------------------------------------------------------------------------
# the conversion
# ---------------------------------------------------------------------------
def _live_topic(card: dict, kind: str, first_line: str) -> dict:
    """A topic shape for a live signal.

    The live layer names its own signal kinds, so the bridge declares a topic for
    them instead of forcing a live signal into one of the editorial TOPICS in
    ``opportunity.py``. Same fields, so ``build_opportunity`` scores it with the
    published rules and nothing is special-cased inside the engine.
    """
    return {
        "key": f"live-{_slug(kind)}",
        "label": f"{card.get('name', card['id'])} · {kind}",
        "keywords": [],
        "business_type": "live signal",
        "title": f"{card.get('name', card['id'])}: {kind}",
        "what_they_need": first_line,
        "money_base": 60,
        "feasibility_base": 70,
    }


def _ensure_parent_opportunity(opp: dict, source_url: str) -> str:
    """Make sure the claim store has the opportunity the claims hang off."""
    opp_id = opp["id"]
    if memory.get_opportunity(opp_id) is None:
        memory.create_opportunity(
            title=opp["title"],
            source_url=source_url,
            opp_id=opp_id,
            status="open",
        )
    return opp_id


def _convert_source(conn, card: dict, emitted: list[dict]) -> dict:
    """Turn one LIVE source's signals into stored signals + cited claims."""
    sid = card["id"]
    source_label = f"{SIGNAL_SOURCE_PREFIX}{sid}"
    source_url = str(card.get("source_url") or card.get("docs") or "").strip()
    captured_at = str(card.get("captured_at") or _now_iso())
    source_turn = f"live_data:{sid}@{captured_at}"

    # -- 1. the signals become real rows in the operational signals table -----
    by_kind: dict[str, list[dict]] = {}
    signals_by_id: dict[str, dict] = {}
    stored_signals = 0
    for rank, sig in enumerate(emitted, start=1):
        line = str(sig.get("line") or "").strip()
        if not line:
            continue
        kind = str(sig.get("kind") or "SIGNAL")
        row = ingestion.normalize_item(
            source_label,
            title=line[:180],
            url=source_url,
            summary=line,
            rank=rank,
            raw={"kind": kind, "severity": sig.get("severity", "info"),
                 "captured_at": captured_at, "source_id": sid},
            fetched_at=captured_at,
        )
        if ingestion._insert_signal(conn, row):
            stored_signals += 1
        signals_by_id[row["id"]] = row
        by_kind.setdefault(kind, []).append({"row": row, "line": line, "signal": sig})

    # Release the write lock BEFORE the claim store is touched: the claim
    # write path audit-logs into this same file, so holding an open write
    # transaction here would deadlock the bridge against itself.
    conn.commit()

    # -- 2 + 3. cluster by kind -> candidate -> cited claims ------------------
    claims_written = 0
    claims_skipped = 0
    opportunity_ids: list[str] = []
    reasons: list[str] = []

    for kind, group in by_kind.items():
        signal_ids = [g["row"]["id"] for g in group]
        cluster = {
            "key": f"live:{sid}:{_slug(kind)}",
            "label": f"{card.get('name', sid)} · {kind}",
            "topic": _live_topic(card, kind, group[0]["line"]),
            "signal_ids": signal_ids,
            "sources": [sid],
            "size": len(signal_ids),
        }
        # Each emitted signal is one claim, and every claim carries its citation.
        claim_payloads = [
            {
                "text": g["line"],
                "signal_id": g["row"]["id"],
                "kind": kind,
                "source_url": source_url,
                "source_turn": source_turn,
            }
            for g in group
        ]
        try:
            opp = opportunity.build_opportunity(cluster, signals_by_id, claims=claim_payloads)
        except opportunity.UncitedOpportunity as exc:
            # The hard gate refused the candidate: nothing is written for it.
            reasons.append(f"{kind}: {exc.reason}")
            continue

        opp_id = _ensure_parent_opportunity(opp, source_url)
        existing = {
            (str(c.get("text", "")), str(c.get("source_turn", "")))
            for c in memory.list_claims(opportunity_id=opp_id, limit=1000)
        }
        wrote_here = 0
        for claim in opp.get("claims") or []:
            key = (claim["text"], claim["source_turn"])
            if key in existing:
                claims_skipped += 1
                continue
            memory.create_claim(
                opportunity_id=opp_id,
                text=claim["text"],
                source_url=claim["source_url"],
                source_turn=claim["source_turn"],
                captured_at=captured_at,
            )
            existing.add(key)
            claims_written += 1
            wrote_here += 1
        opportunity_ids.append(opp_id)
        log.info("[%s] %s %s -> %d claim(s) on opportunity %s",
                 COMPONENT_NAME, sid, kind, wrote_here, opp_id)

    status = STATUS_OK if not reasons else STATUS_ERROR
    reason = "; ".join(reasons) if reasons else str(card.get("detail") or "")
    return _entry(
        card, status,
        signals=len(signals_by_id),
        claims_written=claims_written,
        claims_skipped=claims_skipped,
        opportunities=opportunity_ids,
        stored_signals=stored_signals,
        reason=reason,
    )


# ---------------------------------------------------------------------------
# the public entry point
# ---------------------------------------------------------------------------
def ingest_live_signals(conn, sources=None) -> dict:
    """Convert the live layer's current signals into cited opportunity claims.

    ``conn``    operational SQLite connection (``orchestrator.db.connect()``).
    ``sources`` optional iterable of source ids; ``None`` means every adapter.

    Returns ``{source_id: {status, signals, claims_written, ...}}``. A source that
    answered 401/402/403 is ``DEGRADED`` with its literal reason and always
    reports ``claims_written: 0`` — a refusal never becomes a claim.
    """
    global _LAST

    snap = live_data.snapshot()
    wanted = None
    if sources is not None:
        wanted = {str(s).strip() for s in sources if str(s).strip()}

    summary: dict[str, dict] = {}
    for card in snap.get("sources") or []:
        sid = card.get("id", "")
        if wanted is not None and sid not in wanted:
            continue

        refused, _code = _refusal(card)
        if refused:
            # Never fabricate a claim from a source that said no — this is the
            # mapbox-without-a-token path (NEEDS KEY, zero rows) as much as it is
            # Massive's 403.
            summary[sid] = _entry(
                card, STATUS_DEGRADED, signals=0, claims_written=0,
                reason=_literal_reason(card),
            )
            continue

        if card.get("status") != live_data.LIVE:
            summary[sid] = _entry(
                card, STATUS_ERROR, signals=0, claims_written=0,
                reason=_literal_reason(card) or "no live data to convert",
            )
            continue

        emitted = card.get("signals") or []
        if not emitted:
            summary[sid] = _entry(
                card, STATUS_OK, signals=0, claims_written=0,
                reason="LIVE, but the rows fired no signal rule",
            )
            continue

        try:
            summary[sid] = _convert_source(conn, card, emitted)
        except Exception as exc:  # a bridge crash must not fake a claim
            log.warning("live ingest failed for %s: %s", sid, exc)
            summary[sid] = _entry(
                card, STATUS_ERROR, signals=0, claims_written=0,
                reason=f"{type(exc).__name__}: {exc}",
            )

    try:
        conn.commit()
    except Exception:  # pragma: no cover - defensive
        pass

    totals = {
        "sources": len(summary),
        "signals": sum(e["signals"] for e in summary.values()),
        "claims_written": sum(e["claims_written"] for e in summary.values()),
        "degraded": sum(1 for e in summary.values() if e["status"] == STATUS_DEGRADED),
        "errors": sum(1 for e in summary.values() if e["status"] == STATUS_ERROR),
    }
    _LAST = {"at": _now_iso(), "summary": summary, "totals": totals}
    log.info("[%s] ingest: %s", COMPONENT_NAME, totals)
    return summary


def last_ingest() -> dict | None:
    """The most recent ingest result (for the Live Data page strip)."""
    return _LAST


def reset_for_tests() -> None:
    """Test hook: forget the remembered ingest result."""
    global _LAST
    _LAST = None
