"""Offline, deterministic retrieval baseline. Python 3.11+, standard library only."""
import json
import re
import sys
from dataclasses import dataclass

@dataclass(frozen=True)
class Document:
    id: str
    text: str
    audience: str = "public"

DOCS = (
    Document("D1", "Retry timeout requests with backoff."),
    Document("D2", "Rotate access keys every month."),
    Document("D3", "Private incident recovery password.", "restricted"),
)

def terms(text):
    return set(re.findall(r"[a-z0-9]+", text.lower()))

def answer(query, docs=DOCS, threshold=0.5):
    if not isinstance(query, str) or len(query) > 2000:
        raise ValueError("query must be a string of at most 2000 characters")
    if not 0 < threshold <= 1:
        raise ValueError("threshold must be in (0, 1]")
    if len({d.id for d in docs}) != len(docs):
        raise ValueError("duplicate document ID")
    q = terms(query)
    candidates = []
    for doc in docs:
        if doc.audience != "public":
            continue  # Filter before ranking or constructing the trace.
        score = len(q & terms(doc.text)) / len(q) if q else 0.0
        candidates.append((score, doc.id, doc.text))
    candidates.sort(key=lambda row: (-row[0], row[1]))
    trace = [{"id": d, "score": s} for s, d, _ in candidates]
    if not candidates or candidates[0][0] < threshold:
        return {"status": "abstain", "text": None, "source": None, "trace": trace}
    _, doc_id, text = candidates[0]
    return {"status": "evidence", "text": text, "source": doc_id, "trace": trace}

if __name__ == "__main__":
    query = " ".join(sys.argv[1:]) or "timeout retry"
    print(json.dumps(answer(query), indent=2))
