"""Warrant-chain lookup — Phase 3 of `#000031`.

Read-only helper that returns the set of ``document_root`` values
which have at least one ``derivations`` row written by the warrant
resolver (``process_id LIKE 'warrant-resolver-v1%'``). The verifier
consults this set when a per-claim ``warrant_check`` would otherwise
fire ``WARRANT_MISSING`` — if the cited chunk's document is a
claim-pack record with a Merkle-bound primary-source backing, the
warrant chain DOES exist (just not at the lexical-anchor level), so
the missing-anchor demote is suppressed and a positive
``WARRANT_PROVEN`` annotation flows through to the render layer.

Pure-SQL lookup; one query per Q&A run; result is a frozenset for
hashing / cheap membership tests across many claim verifications.
"""

from __future__ import annotations

from pathlib import Path
import sqlite3


_WARRANT_PROCESS_PREFIX = "warrant-resolver-v1"


def warrant_chain_lookup(shards_dir: str | Path) -> frozenset[str]:
    """Return the frozenset of ``core_root`` values that have a
    warrant-resolver derivation row in any shard under ``shards_dir``.

    Walks every ``*.db`` under both ``<shards_dir>/`` (main numbered
    shards holding claim-pack records) AND ``<shards_dir>/../crawl/``
    (textbook substrate shards may also hold derivations). Tolerates
    missing tables — shards that don't have a ``derivations`` schema
    yet contribute zero rows without raising.

    Returns frozenset for hashable / cheap-membership use in the
    verifier hot path.
    """
    shards_dir = Path(shards_dir).expanduser()
    candidates: list[Path] = []
    if shards_dir.is_dir():
        for db in sorted(shards_dir.glob("*.db")):
            candidates.append(db)
    sibling = shards_dir.parent / "crawl"
    if sibling.is_dir():
        for db in sorted(sibling.glob("*.db")):
            if db.name.startswith(("crawl_russell_", "qa.", "snapshots.")):
                continue
            candidates.append(db)

    roots: set[str] = set()
    for db_path in candidates:
        try:
            conn = sqlite3.connect(str(db_path))
        except sqlite3.Error:
            continue
        try:
            try:
                rows = conn.execute(
                    "SELECT DISTINCT core_root FROM derivations "
                    "WHERE process_id LIKE ? || '%'",
                    (_WARRANT_PROCESS_PREFIX,),
                ).fetchall()
            except sqlite3.OperationalError:
                # No derivations table on this shard.
                continue
            for (core_root,) in rows:
                if core_root:
                    roots.add(core_root)
        finally:
            conn.close()

    return frozenset(roots)


def has_warrant_chain(
    source_roots: list[str] | tuple[str, ...] | set[str] | frozenset[str],
    warrant_chain_roots: frozenset[str],
) -> bool:
    """True if any of ``source_roots`` is in ``warrant_chain_roots``.

    Cheap membership test — no DB call, no allocation beyond the
    frozenset lookup. Used in the verifier per-claim hot path: given
    the list of cited evidence objects' ``source_root`` values, decide
    whether to suppress ``WARRANT_MISSING``.
    """
    if not warrant_chain_roots:
        return False
    return any(r in warrant_chain_roots for r in source_roots)
