"""REAL ingestion layer — the senses of the orchestrator.

This module replaces the old ``IngestionStub``. It handles the INGESTED state and
pulls *actual* signals from the outside world over plain HTTP, using only free
sources that need no API key:

    * Hacker News front page   — official Firebase API (topstories + item)
    * Reddit public JSON       — r/smallbusiness, r/Entrepreneur (proper UA)
    * RSS/Atom feeds           — TechCrunch, BBC Business, Lobsters

Every fetched item is normalised into ONE shape::

    {id, source, title, url, summary, score, rank, fetched_at, raw}

``id`` is a stable hash of ``source|url|title`` so re-running a fetch never
creates duplicates. Signals live in their own SQLite tables (``signals`` and
``ingest_runs``) so the existing jobs/events data is never touched.

Honesty rules enforced here:
    * nothing is fabricated — a source that fails is recorded as failed;
    * if every source fails the run stores zero signals and says so;
    * every run appends one real entry to the existing hash-chained audit log
      (kind ``ingest_run``) with per-source counts and error strings;
    * no note is ever prefixed with ``STUB`` — this component does real work.
"""

from __future__ import annotations

import hashlib
import html as html_mod
import json
import logging
import re
import time
import urllib.error
import urllib.request
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone

from . import state_machine as sm
from . import audit
from .db import CURRENT_CONN, LOCK, connect, init_db
from .events import utcnow
from .registry import Component, Registry

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

#: Identifies us honestly to every source we touch (Reddit blocks blank UAs).
USER_AGENT = "Jarvis/1.0 (personal research assistant; +https://jarvis.llmscape.com/support.html)"
TIMEOUT = 15.0
MAX_SUMMARY = 400
MAX_TITLE = 300


# --------------------------------------------------------------------------
# HTTP
# --------------------------------------------------------------------------

def http_get(url: str, *, headers: dict | None = None, timeout: float = TIMEOUT) -> bytes:
    """One GET with a short timeout. Raises on any failure — never invents data."""
    hdrs = {"User-Agent": USER_AGENT, "Accept": "*/*"}
    if headers:
        hdrs.update(headers)
    req = urllib.request.Request(url, headers=hdrs)
    with urllib.request.urlopen(req, timeout=timeout) as resp:  # noqa: S310 - fixed https URLs
        return resp.read()


def _describe_error(exc: BaseException) -> str:
    if isinstance(exc, urllib.error.HTTPError):
        return f"HTTP {exc.code} {exc.reason}"
    if isinstance(exc, urllib.error.URLError):
        return f"network error: {exc.reason}"
    if isinstance(exc, (TimeoutError, OSError)) and "timed out" in str(exc).lower():
        return f"timeout: {exc}"
    return f"{type(exc).__name__}: {exc}"


# --------------------------------------------------------------------------
# Normalisation — one shape for every source
# --------------------------------------------------------------------------

_TAG_RE = re.compile(r"<[^>]+>")
_WS_RE = re.compile(r"\s+")


def _clean(text) -> str:
    if text is None:
        return ""
    s = html_mod.unescape(str(text))
    s = _TAG_RE.sub(" ", s)
    return _WS_RE.sub(" ", s).strip()


def stable_id(source: str, url: str | None, title: str | None) -> str:
    """Deterministic id from source + url + title (16 hex chars)."""
    key = f"{source}|{(url or '').strip()}|{(title or '').strip()}"
    return hashlib.sha256(key.encode("utf-8")).hexdigest()[:16]


def _as_int(value):
    """Best-effort int for scores/ranks that arrive as strings. None if not numeric."""
    if isinstance(value, bool) or value is None:
        return None
    if isinstance(value, (int, float)):
        return int(value)
    try:
        return int(float(str(value).strip()))
    except (TypeError, ValueError):
        return None


def normalize_item(
    source: str,
    *,
    title,
    url: str = "",
    summary="",
    score=None,
    rank=None,
    raw=None,
    fetched_at: str | None = None,
) -> dict:
    """Turn any source-specific item into the one common signal shape."""
    title_s = _clean(title)[:MAX_TITLE]
    url_s = (url or "").strip()
    summary_s = _clean(summary)[:MAX_SUMMARY]
    return {
        "id": stable_id(source, url_s, title_s),
        "source": source,
        "title": title_s,
        "url": url_s,
        "summary": summary_s,
        "score": _as_int(score),
        "rank": _as_int(rank),
        "fetched_at": fetched_at or utcnow(),
        "raw": raw if isinstance(raw, dict) else {"value": raw},
    }


SIGNAL_KEYS = ("id", "source", "title", "url", "summary", "score", "rank", "fetched_at", "raw")


def coerce_signal(source: str, item) -> dict:
    """Accept either an already-normalised signal or a loose dict."""
    if isinstance(item, dict) and all(k in item for k in SIGNAL_KEYS):
        out = {k: item[k] for k in SIGNAL_KEYS}
        out["source"] = out["source"] or source
        return out
    if isinstance(item, dict):
        return normalize_item(
            source,
            title=item.get("title", ""),
            url=item.get("url", ""),
            summary=item.get("summary") or item.get("description") or "",
            score=item.get("score"),
            rank=item.get("rank"),
            raw=item.get("raw", item),
        )
    return normalize_item(source, title=str(item), raw={"value": item})


# --------------------------------------------------------------------------
# Sources (all free, no API key)
# --------------------------------------------------------------------------

def fetch_hackernews(limit: int = 15) -> list[dict]:
    """Official HN Firebase API: topstories.json then one item.json per story."""
    ids = json.loads(http_get("https://hacker-news.firebaseio.com/v0/topstories.json"))
    if not isinstance(ids, list):
        raise ValueError("unexpected topstories payload (not a list)")
    ids = ids[: max(1, limit)]

    def one(story_id):
        try:
            return json.loads(
                http_get(f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json")
            )
        except Exception as exc:  # one bad item must not kill the source
            log.warning("hn item %s failed: %s", story_id, _describe_error(exc))
            return None

    with ThreadPoolExecutor(max_workers=8) as pool:
        items = list(pool.map(one, ids))

    out: list[dict] = []
    rank = 0
    for it in items:
        if not isinstance(it, dict) or not it.get("title"):
            continue
        rank += 1
        url = it.get("url") or f"https://news.ycombinator.com/item?id={it.get('id')}"
        summary = it.get("text") or (
            f"HN story by {it.get('by')} · {it.get('descendants', 0)} comments"
        )
        out.append(
            normalize_item(
                "hackernews",
                title=it["title"],
                url=url,
                summary=summary,
                score=it.get("score"),
                rank=rank,
                raw=it,
            )
        )
    return out


def fetch_reddit(subreddit: str, limit: int = 25) -> list[dict]:
    """Reddit's public JSON endpoint. Needs a real User-Agent or it 403s."""
    url = f"https://www.reddit.com/r/{subreddit}/top.json?t=day&limit={int(limit)}"
    body = http_get(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
    data = json.loads(body)
    children = (data.get("data") or {}).get("children") or []
    out: list[dict] = []
    for rank, child in enumerate(children, 1):
        d = (child or {}).get("data") or {}
        if not d.get("title"):
            continue
        out.append(
            normalize_item(
                f"reddit/{subreddit}",
                title=d.get("title"),
                url="https://www.reddit.com" + str(d.get("permalink") or ""),
                summary=d.get("selftext") or f"r/{subreddit} · {d.get('num_comments', 0)} comments",
                score=d.get("score"),
                rank=rank,
                raw=d,
            )
        )
    return out


def _local(tag: str) -> str:
    return tag.rsplit("}", 1)[-1].lower()


def _child_text(el, *names) -> str:
    for child in el:
        if _local(child.tag) in names:
            if child.text and child.text.strip():
                return child.text.strip()
            href = child.attrib.get("href")
            if href:
                return href
    return ""


def fetch_rss(source_name: str, feed_url: str, limit: int = 15) -> list[dict]:
    """Parse RSS 2.0 or Atom with the stdlib (no feedparser dependency)."""
    body = http_get(feed_url, headers={"Accept": "application/rss+xml, application/atom+xml, */*"})
    root = ET.fromstring(body)
    entries = [el for el in root.iter() if _local(el.tag) in ("item", "entry")]
    out: list[dict] = []
    for rank, el in enumerate(entries[: max(1, limit)], 1):
        title = _child_text(el, "title")
        if not title:
            continue
        link = _child_text(el, "link", "guid", "id")
        summary = _child_text(el, "description", "summary", "content", "encoded")
        out.append(
            normalize_item(
                source_name,
                title=title,
                url=link,
                summary=summary,
                score=None,
                rank=rank,
                raw={
                    "feed": feed_url,
                    "title": title,
                    "link": link,
                    "published": _child_text(el, "pubdate", "published", "updated"),
                },
            )
        )
    return out


#: The live source list. Each entry is {name, kind, url, fetch(limit) -> signals}.
SOURCES: list[dict] = [
    {
        "name": "hackernews",
        "kind": "api",
        "url": "https://hacker-news.firebaseio.com/v0/topstories.json",
        "fetch": lambda limit: fetch_hackernews(limit),
    },
    {
        "name": "reddit/smallbusiness",
        "kind": "json",
        "url": "https://www.reddit.com/r/smallbusiness/top.json?t=day",
        "fetch": lambda limit: fetch_reddit("smallbusiness", limit),
    },
    {
        "name": "reddit/Entrepreneur",
        "kind": "json",
        "url": "https://www.reddit.com/r/Entrepreneur/top.json?t=day",
        "fetch": lambda limit: fetch_reddit("Entrepreneur", limit),
    },
    {
        "name": "rss/techcrunch",
        "kind": "rss",
        "url": "https://techcrunch.com/feed/",
        "fetch": lambda limit: fetch_rss("rss/techcrunch", "https://techcrunch.com/feed/", limit),
    },
    {
        "name": "rss/bbc-business",
        "kind": "rss",
        "url": "https://feeds.bbci.co.uk/news/business/rss.xml",
        "fetch": lambda limit: fetch_rss("rss/bbc-business", "https://feeds.bbci.co.uk/news/business/rss.xml", limit),
    },
    {
        "name": "rss/lobsters",
        "kind": "rss",
        "url": "https://lobste.rs/rss",
        "fetch": lambda limit: fetch_rss("rss/lobsters", "https://lobste.rs/rss", limit),
    },
]



# Public keyless senses sources. Keep these in ingestion.SOURCES, not live_data.SOURCES.
from . import senses_sources as _senses_sources

_existing_senses_names = {source["name"] for source in SOURCES}
SOURCES.extend(
    source for source in _senses_sources.senses_sources()
    if source["name"] not in _existing_senses_names
)

def source_describe() -> list[dict]:
    return [{"name": s["name"], "kind": s.get("kind", ""), "url": s.get("url", "")} for s in SOURCES]


# --------------------------------------------------------------------------
# Persistence
# --------------------------------------------------------------------------

def _insert_signal(conn, sig: dict) -> bool:
    """INSERT OR IGNORE by stable id. Returns True when the row was new."""
    cur = conn.execute(
        """INSERT OR IGNORE INTO signals
           (id, source, title, url, summary, score, rank, fetched_at, raw, first_seen_at)
           VALUES (?,?,?,?,?,?,?,?,?,?)""",
        (
            sig["id"],
            sig["source"],
            sig["title"],
            sig["url"],
            sig["summary"],
            sig["score"],
            sig["rank"],
            sig["fetched_at"],
            json.dumps(sig["raw"], sort_keys=True, default=str),
            utcnow(),
        ),
    )
    return cur.rowcount > 0


def _row_to_signal(row) -> dict:
    d = dict(row)
    try:
        d["raw"] = json.loads(d.get("raw") or "{}")
    except (ValueError, TypeError):
        d["raw"] = {}
    return d


def list_signals(source: str | None = None, limit: int = 200) -> list[dict]:
    init_db()
    limit = max(1, min(int(limit), 2000))
    conn = connect()
    try:
        if source:
            rows = conn.execute(
                "SELECT * FROM signals WHERE source = ? ORDER BY COALESCE(rank, 9999), fetched_at DESC LIMIT ?",
                (source, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                "SELECT * FROM signals ORDER BY source, COALESCE(rank, 9999), fetched_at DESC LIMIT ?",
                (limit,),
            ).fetchall()
        return [_row_to_signal(r) for r in rows]
    finally:
        conn.close()


def grouped_signals(limit_per_source: int = 25) -> dict[str, list[dict]]:
    """Signals grouped by source, newest fetch first, rank order within a source."""
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM signals ORDER BY source, COALESCE(rank, 9999), fetched_at DESC"
        ).fetchall()
    finally:
        conn.close()
    grouped: dict[str, list[dict]] = {}
    for row in rows:
        sig = _row_to_signal(row)
        bucket = grouped.setdefault(sig["source"], [])
        if len(bucket) < limit_per_source:
            bucket.append(sig)
    return grouped


def signal_counts() -> dict:
    init_db()
    conn = connect()
    try:
        total = conn.execute("SELECT COUNT(*) AS n FROM signals").fetchone()["n"]
        by_source = {
            r["source"]: r["n"]
            for r in conn.execute(
                "SELECT source, COUNT(*) AS n FROM signals GROUP BY source ORDER BY source"
            ).fetchall()
        }
        last = conn.execute(
            "SELECT fetched_at FROM signals ORDER BY first_seen_at DESC LIMIT 1"
        ).fetchone()
    finally:
        conn.close()
    return {
        "total": total,
        "by_source": by_source,
        "sources_with_signals": len(by_source),
        "last_fetched_at": last["fetched_at"] if last else None,
    }


def list_runs(limit: int = 10) -> list[dict]:
    init_db()
    conn = connect()
    try:
        rows = conn.execute(
            "SELECT * FROM ingest_runs ORDER BY id DESC LIMIT ?", (max(1, int(limit)),)
        ).fetchall()
    finally:
        conn.close()
    return [_row_to_run(r) for r in rows]


def get_run(run_id: int) -> dict | None:
    init_db()
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM ingest_runs WHERE id = ?", (int(run_id),)).fetchone()
    finally:
        conn.close()
    return _row_to_run(row) if row else None


def _row_to_run(row) -> dict:
    d = dict(row)
    for key in ("sources", "errors"):
        try:
            d[key] = json.loads(d.get(key) or "[]")
        except (ValueError, TypeError):
            d[key] = []
    return d


# --------------------------------------------------------------------------
# The run
# --------------------------------------------------------------------------

def _build_note(trigger: str, per_source: list[dict], fetched_total: int, new_total: int,
                errors: list[dict], duration_ms: int) -> str:
    attempted = len(per_source)
    ok_sources = [s for s in per_source if s["ok"]]
    head = (
        f"REAL FETCH (trigger={trigger}): {attempted} source(s) attempted, "
        f"{fetched_total} item(s) fetched, {new_total} new after dedupe, "
        f"{len(ok_sources)} source(s) ok, {len(errors)} failed, {duration_ms}ms"
    )
    if errors:
        detail = "; ".join(f"{e['source']} ({e['error']})" for e in errors)
        head += f". Failed: {detail}"
    if fetched_total == 0:
        head += ". No signals were stored and nothing was fabricated."
    return head


def run_ingest(
    sources: list[dict] | None = None,
    limit_per_source: int = 15,
    *,
    write_audit: bool = True,
    trigger: str = "manual",
) -> dict:
    """Fetch every source, normalise, dedupe, persist, and audit the run.

    A failing source never aborts the run: it is recorded as failed in the run
    row and in the audit note. Zero signals is a valid, honest outcome.
    """
    init_db()
    sources = list(SOURCES if sources is None else sources)
    started_at = utcnow()
    t0 = time.time()

    per_source: list[dict] = []
    errors: list[dict] = []
    fetched_total = 0
    new_total = 0
    seen: set[str] = set()

    for spec in sources:
        name = spec.get("name") or "unknown"
        try:
            items = spec["fetch"](limit_per_source) or []
        except Exception as exc:  # graceful failure — recorded, never hidden
            msg = _describe_error(exc)
            errors.append({"source": name, "error": msg})
            per_source.append(
                {"source": name, "kind": spec.get("kind", ""), "ok": False,
                 "fetched": 0, "new": 0, "error": msg}
            )
            log.warning("ingest source %s failed: %s", name, msg)
            continue

        signals: list[dict] = []
        for item in items:
            try:
                signals.append(coerce_signal(name, item))
            except Exception as exc:  # malformed item: skip, do not invent
                log.warning("ingest source %s item skipped: %s", name, _describe_error(exc))

        uniq: dict[str, dict] = {}
        for sig in signals:
            uniq.setdefault(sig["id"], sig)
        fetched_total += len(uniq)

        new_here = 0
        ambient = CURRENT_CONN.get()
        if ambient is not None:
            # Called from inside another component's transaction: join it.
            for sig in uniq.values():
                if sig["id"] in seen:
                    continue
                if _insert_signal(ambient, sig):
                    new_here += 1
                    seen.add(sig["id"])
        else:
            with LOCK:
                conn = connect()
                try:
                    for sig in uniq.values():
                        if sig["id"] in seen:
                            continue
                        if _insert_signal(conn, sig):
                            new_here += 1
                            seen.add(sig["id"])
                    conn.commit()
                finally:
                    conn.close()

        new_total += new_here
        per_source.append(
            {"source": name, "kind": spec.get("kind", ""), "ok": True,
             "fetched": len(uniq), "new": new_here, "error": None}
        )
        log.info("ingest source %s: fetched=%d new=%d", name, len(uniq), new_here)

    finished_at = utcnow()
    duration_ms = int((time.time() - t0) * 1000)
    note = _build_note(trigger, per_source, fetched_total, new_total, errors, duration_ms)

    ambient = CURRENT_CONN.get()
    if ambient is not None:
        run_id, event = _persist_run(ambient, started_at, finished_at, duration_ms,
                                     fetched_total, new_total, per_source, errors,
                                     note, trigger, write_audit)
    else:
        with LOCK:
            conn = connect()
            try:
                run_id, event = _persist_run(conn, started_at, finished_at, duration_ms,
                                             fetched_total, new_total, per_source, errors,
                                             note, trigger, write_audit)
                conn.commit()
            finally:
                conn.close()

    log.info("ingest run #%s: %s", run_id, note)
    return {
        "id": run_id,
        "started_at": started_at,
        "finished_at": finished_at,
        "duration_ms": duration_ms,
        "trigger": trigger,
        "sources": per_source,
        "errors": errors,
        "fetched_total": fetched_total,
        "new_total": new_total,
        "note": note,
        "event_id": event["id"] if event else None,
        "counts": signal_counts(),
    }


def _persist_run(conn, started_at, finished_at, duration_ms, fetched_total, new_total,
         per_source, errors, note, trigger, write_audit):
    """Insert the run row (+ audit event) on the given connection. No commit here."""
    cur = conn.execute(
        """INSERT INTO ingest_runs
           (started_at, finished_at, duration_ms, fetched_total, new_total,
            sources, errors, note, trigger, event_id)
           VALUES (?,?,?,?,?,?,?,?,?,NULL)""",
        (
            started_at, finished_at, duration_ms, fetched_total, new_total,
            json.dumps(per_source, sort_keys=True),
            json.dumps(errors, sort_keys=True),
            note, trigger,
        ),
    )
    run_id = cur.lastrowid
    event = None
    if write_audit:
        # ONE write path: the audit layer records the run in the hash-chained
        # ledger and projects the legacy job-centric event in the same transaction.
        row = audit.record(
            "IngestionLayer", "ingest.run", "ingest_run", run_id,
            {
                "trigger": trigger,
                "sources": per_source,
                "errors": errors,
                "fetched_total": fetched_total,
                "new_total": new_total,
                "duration_ms": duration_ms,
                "note": note,
                "real_fetch": True,
            },
            conn=conn,
            legacy={
                "job_id": None,
                "kind": "ingest_run",
                "from_state": None,
                "to_state": sm.INGESTED,
                "note": note,
                "data": {
                    "run_id": run_id,
                    "trigger": trigger,
                    "sources": per_source,
                    "errors": errors,
                    "fetched_total": fetched_total,
                    "new_total": new_total,
                    "duration_ms": duration_ms,
                    "real_fetch": True,
                },
            },
        )
        event = row["legacy_event"]
        conn.execute("UPDATE ingest_runs SET event_id = ? WHERE id = ?", (event["id"], run_id))
    return run_id, event


# --------------------------------------------------------------------------
# The component (handles INGESTED)
# --------------------------------------------------------------------------

class IngestionLayer:
    """The senses: a real component registered as the INGESTED handler.

    Handler contract matches the registry: ``handler(job) -> dict`` with
    ``to_state``, ``note``, ``payload_patch`` and ``data``.

    A job created with ``payload={"fetch": true}`` triggers a real network pull
    during intake. Ordinary jobs do NOT hit the network — they are accepted at
    INGESTED and the note says so, pointing at POST /ingest and the Senses view.
    """

    name = "IngestionLayer"
    handles_state = sm.INGESTED

    def __init__(self, sources: list[dict] | None = None, limit_per_source: int = 15):
        # None means "resolve the live module-level SOURCES at call time", so the
        # source list can be configured/patched without rebuilding the component.
        self._sources = list(sources) if sources is not None else None
        self.limit_per_source = limit_per_source

    @property
    def sources(self) -> list[dict]:
        return list(SOURCES if self._sources is None else self._sources)

    def __call__(self, job: dict) -> dict:
        return self.handle(job)

    def handle(self, job: dict) -> dict:
        payload = job.get("payload") or {}
        want_fetch = bool(payload.get("fetch")) or str(payload.get("mode", "")).lower() == "fetch"
        counts = signal_counts()

        if want_fetch:
            run = run_ingest(
                self.sources,
                self.limit_per_source,
                trigger=f"job:{str(job.get('id', '?'))[:8]}",
            )
            note = f"REAL INGESTION: {run['note']}"
            log.info("[IngestionLayer] job=%s %s", job.get("id"), note)
            return {
                "to_state": sm.INGESTED,
                "note": note,
                "payload_patch": {
                    "_ingestion": {
                        "fetch_performed": True,
                        "run_id": run["id"],
                        "fetched_total": run["fetched_total"],
                        "new_total": run["new_total"],
                        "errors": run["errors"],
                    }
                },
                "data": {
                    "fetch_performed": True,
                    "run_id": run["id"],
                    "sources": run["sources"],
                    "errors": run["errors"],
                    "fetched_total": run["fetched_total"],
                    "new_total": run["new_total"],
                },
            }

        note = (
            f"REAL INGESTION LAYER: job accepted at INGESTED from source={job.get('source')!r}; "
            f"no fetch requested for this job (payload.fetch not set). "
            f"Store holds {counts['total']} real signal(s) from "
            f"{counts['sources_with_signals']} source(s). "
            f"Pull live signals with POST /ingest or the Senses view."
        )
        log.info("[IngestionLayer] job=%s %s", job.get("id"), note)
        return {
            "to_state": sm.INGESTED,
            "note": note,
            "payload_patch": {
                "_ingestion": {
                    "fetch_performed": False,
                    "stored_signals": counts["total"],
                    "sources_with_signals": counts["sources_with_signals"],
                }
            },
            "data": {
                "fetch_performed": False,
                "stored_signals": counts["total"],
                "by_source": counts["by_source"],
            },
        }

    def describe(self) -> dict:
        return {
            "name": self.name,
            "handles_state": self.handles_state,
            "intake": True,
            "sources": [s["name"] for s in self.sources],
        }


def register_ingestion(registry: Registry, sources: list[dict] | None = None) -> IngestionLayer:
    """Register the real layer as the INGESTED handler, replacing IngestionStub."""
    layer = IngestionLayer(sources=sources)
    for stale in ("IngestionStub", layer.name):
        if registry.has(stale):
            registry.unregister(stale)
    registry.register(
        Component(
            name=layer.name,
            handles_state=sm.INGESTED,
            handler=layer,
            description=(
                "REAL ingestion: live Hacker News / Reddit / RSS fetch, normalised + "
                "deduped into SQLite, every run audit-logged."
            ),
            intake=True,
            produces_state=sm.INGESTED,
        )
    )
    return layer


# --------------------------------------------------------------------------
# CLI: python -m orchestrator.ingestion [--limit N]
# --------------------------------------------------------------------------

def main(argv=None) -> int:
    import argparse

    parser = argparse.ArgumentParser(prog="python -m orchestrator.ingestion",
                                     description="Fetch real signals now")
    parser.add_argument("--limit", type=int, default=15, help="items per source")
    parser.add_argument("--json", action="store_true", help="print the full run as JSON")
    args = parser.parse_args(argv)

    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-7s %(name)s: %(message)s")
    run = run_ingest(limit_per_source=args.limit, trigger="cli")
    if args.json:
        print(json.dumps(run, indent=2, default=str))
    else:
        print(run["note"])
        for s in run["sources"]:
            status = "ok  " if s["ok"] else "FAIL"
            print(f"  {status} {s['source']:<22} fetched={s['fetched']:<3} new={s['new']:<3} {s['error'] or ''}")
        print(f"  stored total: {run['counts']['total']}")
    return 0 if run["fetched_total"] or not run["errors"] else 1


if __name__ == "__main__":
    raise SystemExit(main())


# --- senses resilience (appended): bounded retry, no retry on permanent 4xx ---
import time as _time

_http_get_once = http_get


def http_get(url, headers=None, timeout=TIMEOUT, attempts=3):  # noqa: F811
    """Fetch with bounded retry. The last failure is raised, never swallowed."""
    delay = 1.0
    last = None
    for attempt in range(1, max(1, int(attempts)) + 1):
        try:
            return _http_get_once(url, headers=headers, timeout=timeout)
        except Exception as exc:
            last = exc
            code = getattr(exc, "code", None)
            if isinstance(code, int) and 400 <= code < 500 and code != 429:
                raise  # permanent rejection - retrying cannot help
            if attempt < attempts:
                _time.sleep(delay)
                delay *= 2
    raise last


# --- Reddit fallback (appended): JSON -> RSS -> PullPush ---
_fetch_reddit_once = fetch_reddit


def _is_blocked(exc):
    code = getattr(exc, "code", None)
    if isinstance(code, int) and code in (403, 429):
        return True
    text = str(exc)
    return "403" in text or "429" in text


def fetch_reddit(subreddit, limit=25):  # noqa: F811
    """Try Reddit JSON, RSS, then PullPush; report failures if all fail."""
    json_error = None
    try:
        return _fetch_reddit_once(subreddit, limit)
    except Exception as exc:
        if not _is_blocked(exc):
            raise
        json_error = exc

    from .senses_sources import fetch_reddit_rss, fetch_reddit_fallback

    rss_error = None
    try:
        items = fetch_reddit_rss(subreddit, limit)
        if items:
            return items
        rss_error = RuntimeError("RSS returned zero items")
    except Exception as exc:
        rss_error = exc

    try:
        items = fetch_reddit_fallback(subreddit, limit)
        if items:
            return items
        raise RuntimeError("PullPush returned zero items")
    except Exception as exc:
        details = "Reddit endpoints exhausted for %s: JSON=%s; RSS=%s; PullPush=%s" % (
            subreddit,
            _describe_error(json_error) if json_error else "not attempted",
            _describe_error(rss_error) if rss_error else "not attempted",
            _describe_error(exc),
        )
        raise RuntimeError(details) from exc


# --- sources this network cannot reach (Nov 24, 2026) ---
# Reddit is blocked on all three endpoints from here:
#   JSON 403 Blocked, .rss 404/429, PullPush 429.
# The fetchers stay in the code - remove a name here to re-enable it.
DISABLED_SOURCES = {"reddit/smallbusiness", "reddit/Entrepreneur", "bluesky"}
SOURCES[:] = [s for s in SOURCES if s.get("name") not in DISABLED_SOURCES]
