"""THE VERIFICATION LAYER — the immune-system gate.

What this component does that no other one does
-----------------------------------------------
Given an opportunity and the signals it cites, the verifier goes **back out to
the original sources** and re-checks the claim:

    for each cited signal -> re-fetch its URL with an 8s timeout and an honest
    User-Agent -> look for the cited content in what actually came back ->
    record what it saw, verbatim.

It never trusts the stored row. A stored row proves only that something was
fetched once; it does not prove the source still says it.

Verdict model (exactly three outcomes)
-------------------------------------
``VERIFIED``      >= 2 citations independently re-confirmed, none contradicted
``CONTRADICTED``  any citation's source now contradicts the claim: the content
                  is gone (404/410, or a 2xx page that no longer contains the
                  cited text at all)
``UNVERIFIED``    everything else: fewer than 2 confirmations, or all citations
                  were unreachable / blocked / inconclusive

Unreachable is *not* a failure and *not* a pass. A 403 from a sandbox IP, a
timeout, a DNS error or a 5xx is recorded as ``inconclusive`` with the real
error string, and it simply cannot contribute a confirmation.

Determinism
-----------
``evaluate_citation()`` and ``decide_verdict()`` are pure functions of the
fetched content. Same pages in -> same verdict out. No model, no clock in the
decision, no randomness. ``RULE_VERSION`` is stored next to every verdict so a
verdict can be re-read against the exact rule that produced it.

Gate
----
The component refuses to return ``to_state=VERIFIED`` unless the verdict is
``VERIFIED`` (409). Independently, the state-machine boundary refuses the same
transition (see ``service.advance`` -> ``state_machine.assert_verification_gate``),
so a buggy or replaced component cannot bypass the gate.
"""

from __future__ import annotations

import html as html_mod
import json
import logging
import re
import socket
import time
import urllib.error
import urllib.request
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 .errors import ValidationError, VerificationBlocked
from .events import utcnow
from .registry import Component, Registry

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

COMPONENT_NAME = "VerificationLayer"

#: Bumped whenever a rule below changes. Stored with every verdict.
RULE_VERSION = "1.0"

#: Identifies us honestly to every source we re-fetch.
USER_AGENT = (
    "jarvis-verifier/1.0 (local orchestrator; citation re-check; "
    "+https://github.com/local/jarvis)"
)
TIMEOUT = 8.0
MAX_BYTES = 500_000

#: A page with less readable text than this is treated as unreadable (JS shell,
#: block page, empty response) rather than as evidence about the claim.
MIN_VISIBLE_CHARS = 200

#: Fraction of the claim's distinctive tokens that must appear in the fetched
#: text for the source to count as confirming the claim.
SUPPORT_THRESHOLD = 0.5

#: How many independent confirmations ``VERIFIED`` requires.
MIN_CONFIRMATIONS = 2

#: Verdicts — the complete set. Three, no more.
VERIFIED = "VERIFIED"
UNVERIFIED = "UNVERIFIED"
CONTRADICTED = "CONTRADICTED"
VERDICTS = (VERIFIED, UNVERIFIED, CONTRADICTED)

#: Per-citation outcomes.
CONFIRMED = "confirmed"
CONTRADICTED_OUTCOME = "contradicted"
INCONCLUSIVE = "inconclusive"
OUTCOMES = (CONFIRMED, CONTRADICTED_OUTCOME, INCONCLUSIVE)

#: HTTP statuses that mean "the source answered, and the content is gone".
GONE_STATUSES = (404, 410)

#: HTTP statuses that mean "the source answered, but refused to serve us".
BLOCKED_STATUSES = (401, 402, 403, 429, 451)

#: Keywords that make a claim token unhelpful for matching.
STOPWORDS = {
    "the", "a", "an", "and", "or", "of", "to", "in", "on", "for", "with", "as", "at", "by",
    "from", "is", "are", "was", "were", "be", "been", "it", "its", "this", "that", "these",
    "those", "his", "her", "their", "he", "she", "they", "we", "you", "i", "not", "no", "but",
    "after", "before", "over", "into", "than", "then", "so", "if", "will", "would", "can",
    "could", "has", "have", "had", "do", "does", "did", "how", "what", "why", "who", "when",
    "where", "says", "said", "new", "up", "out", "about", "more", "most", "just", "now",
    "http", "https", "www", "com", "here", "there", "says", "into", "your", "our",
}

#: The inspectable rule document served at GET /verification/rules.
RULES = {
    "version": RULE_VERSION,
    "component": COMPONENT_NAME,
    "model_calls": 0,
    "timeout_seconds": TIMEOUT,
    "user_agent": USER_AGENT,
    "verdicts": {
        VERIFIED: f">= {MIN_CONFIRMATIONS} citations independently re-confirmed and 0 contradicted",
        CONTRADICTED: (
            "any citation's source now contradicts the claim: HTTP 404/410 (content gone) or a "
            "2xx page with >= 200 readable chars that contains none of the claim's tokens"
        ),
        UNVERIFIED: "fewer than 2 confirmations, or every citation inconclusive/unreachable",
    },
    "citation_checks": {
        "claim_text": "the stored signal's title (fallback: evidence title)",
        "claim_tokens": "lowercased alphanumeric tokens of length >= 3, stopwords removed, first 12 kept, deduped",
        "support_threshold": SUPPORT_THRESHOLD,
        "min_visible_chars": MIN_VISIBLE_CHARS,
        "confirmed": f">= {int(SUPPORT_THRESHOLD * 100)}% of claim tokens found in the fetched visible text",
        "contradicted": "HTTP 404/410, or a 2xx page with enough readable text that contains 0 claim tokens",
        "inconclusive": (
            "timeout / DNS / TLS / connection error / 401,403,429,451 / 5xx / < 200 readable chars / "
            "0 < token coverage < support threshold"
        ),
        "unreachable_is_not_a_pass": True,
    },
    "deterministic": True,
    "audit": "one verification_run event per run in the existing hash-chained log",
}


# --------------------------------------------------------------------------
# Text handling
# --------------------------------------------------------------------------

_SCRIPT_RE = re.compile(r"(?is)<(script|style|noscript|template)[^>]*>.*?</\1>")
_TAG_RE = re.compile(r"(?s)<[^>]+>")
_WS_RE = re.compile(r"\s+")
_TOKEN_RE = re.compile(r"[a-z0-9][a-z0-9'\-\.]*")


def _decode(body: bytes, content_type: str) -> str:
    charset = "utf-8"
    m = re.search(r"charset=([\w\-]+)", content_type or "", re.I)
    if m:
        charset = m.group(1)
    try:
        return body.decode(charset, errors="replace")
    except (LookupError, TypeError):
        return body.decode("utf-8", errors="replace")


def _json_strings(obj, out: list[str], depth: int = 0) -> None:
    """Collect human-readable strings out of a JSON payload (bounded)."""
    if depth > 6 or len(out) > 200:
        return
    if isinstance(obj, str):
        if obj.strip():
            out.append(obj)
    elif isinstance(obj, dict):
        for key in ("title", "headline", "text", "selftext", "body", "description",
                    "summary", "content", "name", "url"):
            if key in obj:
                _json_strings(obj[key], out, depth + 1)
        for key, value in obj.items():
            if key not in ("title", "headline", "text", "selftext", "body", "description",
                           "summary", "content", "name", "url"):
                if isinstance(value, (dict, list)) and len(out) < 200:
                    _json_strings(value, out, depth + 1)
    elif isinstance(obj, list):
        for item in obj[:100]:
            _json_strings(item, out, depth + 1)


def extract_text(body: bytes, content_type: str = "") -> str:
    """Visible text of a fetched response. Pure function of the bytes."""
    raw = _decode(body, content_type)
    ct = (content_type or "").lower()
    stripped = raw.lstrip()[:1]
    if "json" in ct or stripped in "{[":
        try:
            data = json.loads(raw)
        except ValueError:
            data = None
        if data is not None:
            parts: list[str] = []
            _json_strings(data, parts)
            raw = " ".join(parts)
            return _WS_RE.sub(" ", html_mod.unescape(raw)).strip()
    raw = _SCRIPT_RE.sub(" ", raw)
    raw = _TAG_RE.sub(" ", raw)
    return _WS_RE.sub(" ", html_mod.unescape(raw)).strip()


def claim_tokens(text: str) -> list[str]:
    """Distinctive, deterministic tokens of a claim (what we look for in a page)."""
    seen: list[str] = []
    for tok in _TOKEN_RE.findall((text or "").lower()):
        tok = tok.strip(".-'")
        if len(tok) < 3 or tok in STOPWORDS or tok.isdigit() and len(tok) < 3:
            continue
        if tok not in seen:
            seen.append(tok)
    return seen[:12]


def _token_present(token: str, haystack: str) -> bool:
    pattern = r"(?<![a-z0-9])" + re.escape(token) + r"(?![a-z0-9])"
    return re.search(pattern, haystack) is not None


def _excerpt(text: str, limit: int = 220) -> str:
    text = (text or "").strip()
    return text if len(text) <= limit else text[:limit].rstrip() + "…"


# --------------------------------------------------------------------------
# The fetch — real HTTP, honest about every failure
# --------------------------------------------------------------------------

def fetch_url(url: str, *, timeout: float = TIMEOUT, max_bytes: int = MAX_BYTES) -> dict:
    """GET a URL once. Returns a record; NEVER raises and NEVER invents content."""
    started = time.time()
    result = {
        "ok": False,
        "url": url,
        "final_url": url,
        "http_status": None,
        "content_type": "",
        "body": b"",
        "error": None,
        "error_kind": None,
        "duration_ms": 0,
    }
    if not url or not re.match(r"^https?://", url):
        result["error"] = f"no fetchable http(s) URL for this citation (url={url!r})"
        result["error_kind"] = "no_url"
        return result
    try:
        req = urllib.request.Request(
            url,
            headers={
                "User-Agent": USER_AGENT,
                "Accept": "text/html,application/xhtml+xml,application/xml,application/json;q=0.9,*/*;q=0.8",
            },
        )
        with urllib.request.urlopen(req, timeout=timeout) as resp:  # noqa: S310 - absolute URLs
            body = resp.read(max_bytes)
            result.update(
                ok=True,
                final_url=resp.geturl(),
                http_status=getattr(resp, "status", None) or 200,
                content_type=resp.headers.get("Content-Type", "") or "",
                body=body,
            )
    except urllib.error.HTTPError as exc:
        result.update(
            http_status=exc.code,
            error=f"HTTP {exc.code} {exc.reason}",
            error_kind="http_error",
        )
    except urllib.error.URLError as exc:
        reason = exc.reason
        if isinstance(reason, (TimeoutError, socket.timeout)):
            result.update(error=f"timeout after {timeout}s: {reason}", error_kind="timeout")
        else:
            result.update(error=f"network error: {reason}", error_kind="network_error")
    except (TimeoutError, socket.timeout) as exc:
        result.update(error=f"timeout after {timeout}s: {exc}", error_kind="timeout")
    except Exception as exc:  # noqa: BLE001 - any failure is recorded verbatim
        result.update(error=f"{type(exc).__name__}: {exc}", error_kind="fetch_error")
    finally:
        result["duration_ms"] = int((time.time() - started) * 1000)
    return result


#: Indirection so tests can mock every network call: verification.FETCHER = fake.
FETCHER = fetch_url


# --------------------------------------------------------------------------
# Pure evaluation: one citation
# --------------------------------------------------------------------------

def evaluate_citation(
    citation: dict,
    claim_text: str,
    fetched: dict,
    *,
    fetched_at: str | None = None,
) -> dict:
    """Turn (claim, fetched response) into a per-citation evidence record.

    Deterministic: same claim + same response => identical record (apart from
    the timestamp, which is passed in or taken from the fetch).
    """
    tokens = claim_tokens(claim_text)
    rec = {
        "signal_id": citation.get("signal_id"),
        "source": citation.get("source", ""),
        "url": citation.get("url", ""),
        "claim_text": claim_text or "",
        "claim_tokens": tokens,
        "reachable": bool(fetched.get("ok")),
        "content_present": False,
        "supports_claim": False,
        "http_status": fetched.get("http_status"),
        "fetched_at": fetched_at or fetched.get("fetched_at") or utcnow(),
        "outcome": INCONCLUSIVE,
        "reason": "",
        "error": fetched.get("error"),
        "error_kind": fetched.get("error_kind"),
        "final_url": fetched.get("final_url") or citation.get("url", ""),
        "claim_coverage": 0.0,
        "tokens_matched": [],
        "visible_chars": 0,
        "bytes": len(fetched.get("body") or b""),
        "duration_ms": fetched.get("duration_ms", 0),
        "saw": "",
    }

    if not tokens:
        rec["reason"] = "claim_has_no_checkable_tokens"
        rec["saw"] = (
            "No claim text was available to check (no stored title and no tokens), so nothing "
            "could be confirmed or contradicted."
        )
        return rec

    if not fetched.get("ok"):
        status = fetched.get("http_status")
        if status in GONE_STATUSES:
            rec["outcome"] = CONTRADICTED_OUTCOME
            rec["reason"] = "content_gone"
            rec["saw"] = (
                f"{fetched.get('error')} — the source answered and the cited content is NOT at "
                f"this URL any more. Nothing was retrieved."
            )
        elif status in BLOCKED_STATUSES:
            rec["reason"] = "source_blocked"
            rec["saw"] = (
                f"{fetched.get('error')} — the source refused this request (blocked / rate "
                f"limited from this IP). The content was never seen, so this citation is "
                f"INCONCLUSIVE: it neither confirms nor contradicts the claim."
            )
        else:
            rec["reason"] = fetched.get("error_kind") or "source_unreachable"
            rec["saw"] = (
                f"{fetched.get('error')} — nothing was fetched. Recorded as unreachable; this "
                f"citation is INCONCLUSIVE, not verified."
            )
        return rec

    text = extract_text(fetched.get("body") or b"", fetched.get("content_type", ""))
    haystack = text.lower()
    visible = len(text)
    matched = [t for t in tokens if _token_present(t, haystack)]
    coverage = round(len(matched) / len(tokens), 3) if tokens else 0.0

    rec.update(visible_chars=visible, tokens_matched=matched, claim_coverage=coverage)

    if visible < MIN_VISIBLE_CHARS:
        rec["reason"] = "no_readable_text"
        rec["saw"] = (
            f"HTTP {rec['http_status']}, but only {visible} readable character(s) came back "
            f"(JS shell, block page or empty response). Nothing checkable was seen. Excerpt: "
            f"{_excerpt(text) or '(empty)'}"
        )
        return rec

    rec["content_present"] = bool(matched)

    if coverage == 0.0:
        rec["outcome"] = CONTRADICTED_OUTCOME
        rec["reason"] = "content_changed"
        rec["saw"] = (
            f"HTTP {rec['http_status']}, {visible} readable chars, but 0 of {len(tokens)} claim "
            f"tokens found ({', '.join(tokens[:4])}…). The page is serving different content, so "
            f"the source no longer supports the claim. Excerpt: {_excerpt(text)}"
        )
        return rec

    if coverage >= SUPPORT_THRESHOLD:
        rec["outcome"] = CONFIRMED
        rec["supports_claim"] = True
        rec["reason"] = "content_confirmed"
        rec["saw"] = (
            f"HTTP {rec['http_status']}, {visible} readable chars; {len(matched)}/{len(tokens)} "
            f"claim tokens present ({', '.join(matched[:6])}). Excerpt: {_excerpt(text)}"
        )
        return rec

    rec["reason"] = "partial_match"
    rec["saw"] = (
        f"HTTP {rec['http_status']}, {visible} readable chars; only {len(matched)}/{len(tokens)} "
        f"claim tokens present ({', '.join(matched[:6]) or 'none'}). Too little overlap to say the "
        f"source supports the claim. Excerpt: {_excerpt(text)}"
    )
    return rec


# --------------------------------------------------------------------------
# Pure evaluation: the verdict
# --------------------------------------------------------------------------

def decide_verdict(citations: list[dict]) -> dict:
    """The verdict rule. Pure function of the per-citation records."""
    confirmed = [c for c in citations if c.get("outcome") == CONFIRMED]
    contradicted = [c for c in citations if c.get("outcome") == CONTRADICTED_OUTCOME]
    inconclusive = [c for c in citations if c.get("outcome") == INCONCLUSIVE]

    if contradicted:
        verdict = CONTRADICTED
        blocking = contradicted
        reason = (
            f"{len(contradicted)} citation(s) contradicted by their source; a contradiction "
            f"outranks any number of confirmations."
        )
    elif len(confirmed) >= MIN_CONFIRMATIONS:
        verdict = VERIFIED
        blocking = []
        reason = (
            f"{len(confirmed)} citation(s) independently re-confirmed, 0 contradicted "
            f"(rule v{RULE_VERSION})."
        )
    else:
        verdict = UNVERIFIED
        blocking = inconclusive + confirmed
        reason = (
            f"only {len(confirmed)} confirmation(s); {MIN_CONFIRMATIONS} are required and none "
            f"may be contradicted. {len(inconclusive)} citation(s) were inconclusive/unreachable."
        )
    return {
        "verdict": verdict,
        "rule_version": RULE_VERSION,
        "reason": reason,
        "counts": {
            "citations": len(citations),
            "confirmed": len(confirmed),
            "contradicted": len(contradicted),
            "inconclusive": len(inconclusive),
        },
        "blocking": [c.get("signal_id") for c in blocking],
        "confirmed_signal_ids": [c.get("signal_id") for c in confirmed],
        "contradicted_signal_ids": [c.get("signal_id") for c in contradicted],
        "inconclusive_signal_ids": [c.get("signal_id") for c in inconclusive],
    }


def describe_blocking(citations: list[dict], blocking_ids: list[str]) -> str:
    """Human sentence naming the citations that block the transition."""
    by_id = {c.get("signal_id"): c for c in citations}
    parts = []
    for sid in blocking_ids:
        c = by_id.get(sid)
        if not c:
            continue
        parts.append(
            f"{sid} ({c.get('source')} {c.get('url')}) -> {c.get('outcome')}: {c.get('saw')}"
        )
    return "; ".join(parts) if parts else "no citation could be confirmed"


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

def add_tables(conn) -> None:
    """Idempotent schema migration (delegates to db.ensure_verification_schema)."""
    from .db import ensure_verification_schema

    ensure_verification_schema(conn)


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


def list_runs(limit: int = 20, opportunity_id: str | None = None) -> list[dict]:
    init_db()
    limit = max(1, min(int(limit), 500))
    conn = connect()
    try:
        if opportunity_id:
            rows = conn.execute(
                "SELECT * FROM verification_runs WHERE opportunity_id = ? ORDER BY id DESC LIMIT ?",
                (opportunity_id, limit),
            ).fetchall()
        else:
            rows = conn.execute(
                "SELECT * FROM verification_runs ORDER BY id DESC LIMIT ?", (limit,)
            ).fetchall()
        return [_row_to_run(r) for r in rows]
    finally:
        conn.close()


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


def verdict_counts() -> dict:
    """Real counts only. Zero everywhere until something has actually been verified."""
    init_db()
    conn = connect()
    try:
        total_opps = conn.execute("SELECT COUNT(*) AS n FROM opportunities").fetchone()["n"]
        rows = conn.execute(
            "SELECT verdict, COUNT(*) AS n FROM opportunities WHERE verdict IS NOT NULL "
            "GROUP BY verdict"
        ).fetchall()
        runs = conn.execute("SELECT COUNT(*) AS n FROM verification_runs").fetchone()["n"]
        last = conn.execute(
            "SELECT * FROM verification_runs ORDER BY id DESC LIMIT 1"
        ).fetchone()
    finally:
        conn.close()
    by_verdict = {v: 0 for v in VERDICTS}
    for r in rows:
        by_verdict[r["verdict"]] = r["n"]
    verified_opps = sum(by_verdict.values())
    return {
        "opportunities": total_opps,
        "verified": by_verdict[VERIFIED],
        "unverified": by_verdict[UNVERIFIED],
        "contradicted": by_verdict[CONTRADICTED],
        "by_verdict": by_verdict,
        "with_verdict": verified_opps,
        "never_verified": max(0, total_opps - verified_opps),
        "runs": runs,
        "last_run": _row_to_run(last) if last else None,
        "rule_version": RULE_VERSION,
    }


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

def _load_context(opp_id: str) -> tuple[dict, dict]:
    """Opportunity row + {signal_id: signal row}. Read-only, own connection."""
    init_db()
    conn = connect()
    try:
        row = conn.execute("SELECT * FROM opportunities WHERE id = ?", (opp_id,)).fetchone()
        if row is None:
            raise ValidationError(f"no opportunity with id {opp_id!r}")
        opp = dict(row)
        for field in ("evidence", "scores", "cluster_signal_ids", "sources"):
            try:
                opp[field] = json.loads(opp.get(field) or "[]")
            except (ValueError, TypeError):
                opp[field] = {}
        sids = [e.get("signal_id") for e in (opp.get("evidence") or []) if e.get("signal_id")]
        signals: dict[str, dict] = {}
        if sids:
            marks = ",".join("?" for _ in sids)
            for srow in conn.execute(
                f"SELECT id, source, title, url, summary FROM signals WHERE id IN ({marks})",
                sids,
            ).fetchall():
                signals[srow["id"]] = dict(srow)
        return opp, signals
    finally:
        conn.close()


def verify_opportunity(
    opp_id: str,
    *,
    trigger: str = "api",
    job_id: str | None = None,
    fetcher=None,
    write_audit: bool = True,
) -> dict:
    """Re-fetch every citation of one opportunity and record the honest verdict."""
    fetcher = fetcher or FETCHER
    opp, signals = _load_context(opp_id)
    evidence = opp.get("evidence") or []
    if not evidence:
        raise ValidationError(
            f"opportunity {opp_id!r} cites 0 signals; there is nothing to verify"
        )

    started_at = utcnow()
    t0 = time.time()

    def one(citation: dict) -> dict:
        sig = signals.get(citation.get("signal_id")) or {}
        claim = (sig.get("title") or citation.get("title") or "").strip()
        url = (sig.get("url") or citation.get("url") or "").strip()
        cite = dict(citation)
        cite["url"] = url or citation.get("url", "")
        fetched = fetcher(url) if url else {
            "ok": False, "http_status": None, "error": "no URL stored for this citation",
            "error_kind": "no_url", "body": b"", "content_type": "",
        }
        fetched_at = utcnow()
        return evaluate_citation(cite, claim, fetched, fetched_at=fetched_at)

    with ThreadPoolExecutor(max_workers=min(8, max(1, len(evidence)))) as pool:
        citations = list(pool.map(one, evidence))

    outcome = decide_verdict(citations)
    verdict = outcome["verdict"]
    finished_at = utcnow()
    duration_ms = int((time.time() - t0) * 1000)

    counts = outcome["counts"]
    note = (
        f"REAL VERIFICATION v{RULE_VERSION}: opportunity {opp_id} -> {verdict}. "
        f"{counts['citations']} citation(s) re-fetched: {counts['confirmed']} confirmed, "
        f"{counts['contradicted']} contradicted, {counts['inconclusive']} inconclusive/"
        f"unreachable. {outcome['reason']}"
    )
    if verdict != VERIFIED:
        note += f" Blocking: {describe_blocking(citations, outcome['blocking'])}"

    verification_blob = {
        "verdict": verdict,
        "rule_version": RULE_VERSION,
        "reason": outcome["reason"],
        "counts": counts,
        "citations": citations,
        "blocking_signal_ids": outcome["blocking"],
        "verified_at": finished_at,
        "trigger": trigger,
        "real_fetch": True,
    }

    ambient = CURRENT_CONN.get()
    if ambient is not None:
        run_id, event = _persist(
            ambient, started_at, finished_at, duration_ms, opp_id, job_id, verdict,
            outcome, citations, note, trigger, verification_blob, write_audit,
        )
    else:
        with LOCK:
            conn = connect()
            try:
                run_id, event = _persist(
                    conn, started_at, finished_at, duration_ms, opp_id, job_id, verdict,
                    outcome, citations, note, trigger, verification_blob, write_audit,
                )
                conn.commit()
            finally:
                conn.close()

    log.info("[%s] %s", COMPONENT_NAME, note)
    return {
        "id": run_id,
        "opportunity_id": opp_id,
        "job_id": job_id,
        "started_at": started_at,
        "finished_at": finished_at,
        "duration_ms": duration_ms,
        "verdict": verdict,
        "rule_version": RULE_VERSION,
        "reason": outcome["reason"],
        "counts": counts,
        "citations": citations,
        "blocking_signal_ids": outcome["blocking"],
        "note": note,
        "trigger": trigger,
        "event_id": event["id"] if event else None,
    }


def _persist(conn, started_at, finished_at, duration_ms, opp_id, job_id, verdict,
             outcome, citations, note, trigger, verification_blob, write_audit):
    """Insert the run row, update the opportunity, append the audit event. No commit."""
    counts = outcome["counts"]
    cur = conn.execute(
        """INSERT INTO verification_runs
           (started_at, finished_at, duration_ms, opportunity_id, job_id, verdict, rule_version,
            confirmed, contradicted, inconclusive, citations, note, trigger, event_id)
           VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NULL)""",
        (started_at, finished_at, duration_ms, opp_id, job_id, verdict, RULE_VERSION,
         counts["confirmed"], counts["contradicted"], counts["inconclusive"],
         json.dumps(citations, sort_keys=True, default=str), note, trigger),
    )
    run_id = cur.lastrowid
    conn.execute(
        """UPDATE opportunities
           SET verdict = ?, verdict_rule_version = ?, verdict_at = ?, verification_run_id = ?,
               verification = ?, updated_at = ?
           WHERE id = ?""",
        (verdict, RULE_VERSION, finished_at, run_id,
         json.dumps(verification_blob, sort_keys=True, default=str), finished_at, opp_id),
    )
    event = None
    if write_audit:
        # ONE write path: verdict -> ledger row + legacy event projection.
        row = audit.record(
            COMPONENT_NAME, "verification.verdict", "opportunity", opp_id,
            {
                "run_id": run_id,
                "verdict": verdict,
                "rule_version": RULE_VERSION,
                "counts": counts,
                "blocking_signal_ids": outcome["blocking"],
                "reason": outcome["reason"],
                "trigger": trigger,
                "job_id": job_id,
                "real_fetch": True,
            },
            conn=conn,
            legacy={
                "job_id": job_id,
                "kind": "verification_run",
                "from_state": sm.INGESTED,
                "to_state": sm.VERIFIED if verdict == VERIFIED else None,
                "note": note,
                "data": {
                    "run_id": run_id,
                    "opportunity_id": opp_id,
                    "verdict": verdict,
                    "rule_version": RULE_VERSION,
                    "counts": counts,
                    "citations": citations,
                    "blocking_signal_ids": outcome["blocking"],
                    "trigger": trigger,
                    "real_fetch": True,
                    "duration_ms": duration_ms,
                },
            },
        )
        event = row["legacy_event"]
        conn.execute(
            "UPDATE verification_runs SET event_id = ? WHERE id = ?", (event["id"], run_id)
        )
    return run_id, event


def verify_all(opportunities: list[str] | None = None, *, trigger: str = "all", fetcher=None) -> dict:
    """Verify every stored opportunity. Sequential per opportunity (each is parallel inside)."""
    init_db()
    if opportunities is None:
        conn = connect()
        try:
            opportunities = [
                r["id"] for r in conn.execute(
                    "SELECT id FROM opportunities ORDER BY composite_score DESC, id ASC"
                ).fetchall()
            ]
        finally:
            conn.close()

    started_at = utcnow()
    results: list[dict] = []
    errors: list[dict] = []
    for opp_id in opportunities:
        try:
            results.append(verify_opportunity(opp_id, trigger=trigger, fetcher=fetcher))
        except Exception as exc:  # one bad opportunity must not kill the sweep
            log.warning("verify failed for %s: %s", opp_id, exc)
            errors.append({"opportunity_id": opp_id, "error": f"{type(exc).__name__}: {exc}"})

    tally = {v: 0 for v in VERDICTS}
    for r in results:
        tally[r["verdict"]] += 1
    message = (
        f"REAL VERIFICATION SWEEP: {len(results)} opportunity(ies) verified -> "
        f"{tally[VERIFIED]} VERIFIED, {tally[UNVERIFIED]} UNVERIFIED, "
        f"{tally[CONTRADICTED]} CONTRADICTED, {len(errors)} error(s). Rule v{RULE_VERSION}."
    )
    return {
        "started_at": started_at,
        "finished_at": utcnow(),
        "count": len(results),
        "tally": tally,
        "errors": errors,
        "message": message,
        "rule_version": RULE_VERSION,
        "runs": results,
    }


# --------------------------------------------------------------------------
# The gate — facts for a job + refusal messages
# --------------------------------------------------------------------------

def facts_for_job(job: dict, conn=None) -> dict:
    """What the transition boundary needs to know about this job's citations.

    A job is in scope when it is backed by an opportunity or explicitly carries
    evidence rows. Plain manual/seed jobs cite nothing and therefore make no
    factual claim that could be verified.
    """
    payload = job.get("payload") or {}
    opp_id = payload.get("opportunity_id")
    evidence = payload.get("evidence") or []
    cites = bool(opp_id) or bool(evidence)
    facts = {
        "cites_signals": cites,
        "opportunity_id": opp_id,
        "verdict": None,
        "rule_version": None,
        "verification_run_id": None,
        "blocking": [],
        "citations": [],
    }
    if not cites or conn is None:
        return facts

    if opp_id:
        row = conn.execute(
            "SELECT verdict, verdict_rule_version, verification_run_id, verification "
            "FROM opportunities WHERE id = ?",
            (opp_id,),
        ).fetchone()
        if row is not None:
            facts["verdict"] = row["verdict"]
            facts["rule_version"] = row["verdict_rule_version"]
            facts["verification_run_id"] = row["verification_run_id"]
            try:
                blob = json.loads(row["verification"] or "{}")
            except (ValueError, TypeError):
                blob = {}
            facts["citations"] = blob.get("citations") or []
            facts["blocking"] = blob.get("blocking_signal_ids") or []
    else:
        row = conn.execute(
            "SELECT * FROM verification_runs WHERE job_id = ? ORDER BY id DESC LIMIT 1",
            (job.get("id"),),
        ).fetchone()
        if row is not None:
            facts["verdict"] = row["verdict"]
            facts["rule_version"] = row["rule_version"]
            facts["verification_run_id"] = row["id"]
            facts["citations"] = _row_to_run(row)["citations"]
    return facts


def refusal_message(job: dict, facts: dict, to_state: str) -> str:
    verdict = facts.get("verdict") or "NO VERDICT"
    where = facts.get("opportunity_id") or f"job {str(job.get('id'))[:8]}"
    lines = [
        f"verification refused {job.get('state')} -> {to_state} for opportunity {where}: "
        f"verdict is {verdict}"
        + (f" (rule v{facts['rule_version']})" if facts.get("rule_version") else "")
        + "."
    ]
    citations = facts.get("citations") or []
    if citations:
        blocking = [
            c for c in citations
            if c.get("outcome") != CONFIRMED
        ]
        if not blocking:
            blocking = citations
        detail = "; ".join(
            f"{c.get('signal_id')} {c.get('source')} {c.get('url')} -> {c.get('outcome')}: "
            f"{c.get('saw') or c.get('error') or 'no detail'}"
            for c in blocking[:6]
        )
        lines.append(f"Blocking citations: {detail}")
    else:
        lines.append(
            "No verification evidence has been recorded for this opportunity yet — run "
            "POST /opportunities/<id>/verify first."
        )
    return " ".join(lines)


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

class VerificationLayer:
    """Registered INGESTED handler: re-fetch cited sources, gate on the verdict.

    Two behaviours, both honest:

    * job cites signals (opportunity-backed): run a REAL verification, store the
      verdict, and raise ``VerificationBlocked`` (409) unless the verdict is
      ``VERIFIED``.
    * job cites nothing (manual/seed demo job): there is no factual claim to
      re-check. Structural checks only, and the note says exactly that.
    """

    name = COMPONENT_NAME
    handles_state = sm.INGESTED

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

    def handle(self, job: dict) -> dict:
        payload = job.get("payload") or {}
        opp_id = payload.get("opportunity_id")
        evidence = payload.get("evidence") or []

        if not opp_id and not evidence:
            return self._handle_no_citations(job)

        if not opp_id:
            # Evidence but no opportunity row: nothing to persist a verdict onto.
            raise VerificationBlocked(
                f"verification refused INGESTED -> VERIFIED for job {str(job.get('id'))[:8]}: "
                f"the job carries {len(evidence)} evidence row(s) but no opportunity_id, so no "
                f"verdict can be recorded. Create the job via "
                f"POST /opportunities/<id>/queue so its citations are verified.",
                verdict=None,
                details={"verdict": None, "citations": evidence, "opportunity_id": None},
            )

        run = verify_opportunity(
            opp_id,
            trigger=f"job:{str(job.get('id', '?'))[:8]}",
            job_id=job.get("id"),
        )
        facts = {
            "cites_signals": True,
            "opportunity_id": opp_id,
            "verdict": run["verdict"],
            "rule_version": run["rule_version"],
            "citations": run["citations"],
            "blocking": run["blocking_signal_ids"],
        }
        if run["verdict"] != VERIFIED:
            raise VerificationBlocked(
                refusal_message(job, facts, sm.VERIFIED),
                verdict=run["verdict"],
                details={
                    "verdict": run["verdict"],
                    "rule_version": run["rule_version"],
                    "opportunity_id": opp_id,
                    "run_id": run["id"],
                    "citations": run["citations"],
                    "blocking_signal_ids": run["blocking_signal_ids"],
                },
            )

        return {
            "to_state": sm.VERIFIED,
            "note": run["note"],
            "payload_patch": {
                "_verification": {
                    "verdict": run["verdict"],
                    "rule_version": run["rule_version"],
                    "run_id": run["id"],
                    "confirmed": run["counts"]["confirmed"],
                    "contradicted": run["counts"]["contradicted"],
                    "inconclusive": run["counts"]["inconclusive"],
                    "real_fetch": True,
                }
            },
            "data": {
                "run_id": run["id"],
                "opportunity_id": opp_id,
                "verdict": run["verdict"],
                "rule_version": run["rule_version"],
                "counts": run["counts"],
                "citations": run["citations"],
                "real_fetch": True,
            },
        }

    def _handle_no_citations(self, job: dict) -> dict:
        payload = job.get("payload") or {}
        checks = {
            "title_nonempty": bool(str(job.get("title", "")).strip()),
            "source_nonempty": bool(str(job.get("source", "")).strip()),
            "payload_is_object": isinstance(payload, dict),
            "citations": 0,
        }
        note = (
            "NO CITATIONS TO VERIFY: this job cites 0 signals and is not backed by an "
            "opportunity, so there is nothing to re-fetch and NO factual claim was verified. "
            "Structural checks only "
            f"(title={'ok' if checks['title_nonempty'] else 'missing'}, "
            f"source={'ok' if checks['source_nonempty'] else 'missing'}, "
            f"payload={'ok' if checks['payload_is_object'] else 'not an object'}). "
            "Opportunity-backed jobs are re-fetched and gated on a real VERIFIED verdict."
        )
        log.info("[%s] job=%s %s", self.name, job.get("id"), note)
        return {
            "to_state": sm.VERIFIED,
            "note": note,
            "payload_patch": {"_verification": {"citations": 0, "real_fetch": False,
                                                "checks": checks}},
            "data": {"citations": 0, "real_fetch": False, "checks": checks},
        }

    def describe(self) -> dict:
        return {
            "name": self.name,
            "handles_state": self.handles_state,
            "kind": "state",
            "description": "REAL verification: re-fetches every cited source, records what it saw.",
            "rule_version": RULE_VERSION,
        }


def register_verification(registry: Registry) -> Component:
    """Register the verifier as the INGESTED handler, replacing VerificationStub."""
    layer = VerificationLayer()
    for stale in ("VerificationStub", COMPONENT_NAME):
        if registry.has(stale):
            registry.unregister(stale)
    return registry.register(
        Component(
            name=COMPONENT_NAME,
            handles_state=sm.INGESTED,
            handler=layer,
            description=(
                "REAL verification gate: re-fetches each cited source URL, records reachability, "
                "content presence and claim support, and blocks INGESTED -> VERIFIED unless the "
                "verdict is VERIFIED."
            ),
            produces_state=sm.VERIFIED,
        )
    )


def parse_verification(opp: dict) -> dict:
    """Decode the stored ``verification`` JSON blob on an opportunity row.

    ``opportunity.list_opportunities()`` leaves the column as a JSON string, so
    templates would otherwise see a string and silently render the empty state
    even when real evidence exists. Returns {} when nothing was ever recorded.
    """
    raw = opp.get("verification")
    if isinstance(raw, dict):
        return raw
    if not raw:
        return {}
    try:
        blob = json.loads(raw)
    except (ValueError, TypeError):
        return {}
    return blob if isinstance(blob, dict) else {}


def decorate_opportunities(opps: list[dict]) -> list[dict]:
    """Attach a decoded ``verification_blob`` to each opportunity for the UI."""
    out = []
    for opp in opps:
        row = dict(opp)
        row["verification_blob"] = parse_verification(opp)
        out.append(row)
    return out


def rules_document() -> dict:
    return {
        "component": COMPONENT_NAME,
        "rules": RULES,
        "verdicts": list(VERDICTS),
        "outcomes": list(OUTCOMES),
        "gate": (
            "INGESTED -> VERIFIED (and VERIFIED -> BOT_BUILT) is refused with HTTP 409 unless "
            "the opportunity's stored verdict is VERIFIED. Enforced in the component AND at the "
            "state-machine boundary."
        ),
    }
