"""Detect wiki ingest falling behind shipped work (REQ-145).

"Ingest on close" was an instruction, and agents skipped it: the wiki went
nine implemented requests stale with no surface reporting it. It was fixed by
hand on 2026-07-20 and had regrown to eight within a single day. That is a
leak, not a backlog, so it needs a check rather than another reminder.

Why the existing signal cannot catch it: `prd_status.wiki_backfill_pending`
tests for a marker file AND the ABSENCE of `wiki/index.md` — the one-time
backfill for a repo that has just gained a wiki. It correctly reads false
while ongoing ingest rots.

The comparison is deliberately anchored. Counting every implemented request
against the log flags all pre-wiki history as drift (71 of 126 in this repo),
which buries the signal. The baseline is the earliest request the log already
cites: work from before the wiki began is history, not a missed ingest.

Read-only, and never raises — a malformed input degrades to "nothing to
report" rather than breaking a status call.
"""

import argparse
import json
import re
import sys
from pathlib import Path

REQUESTS_REL = ".prd_plugin/state/requests.json"
WIKI_LOG_REL = "wiki/log.md"
WIKI_INDEX_REL = "wiki/index.md"
REQ_ID = re.compile(r"\bREQ-(\d+)\b")


def _number(request_id):
    match = REQ_ID.search(str(request_id or ""))
    return int(match.group(1)) if match else None


def _implemented(root):
    """Implemented request ids, ordered by number."""
    try:
        data = json.loads((Path(root) / REQUESTS_REL).read_text(encoding="utf-8-sig"))
    except (OSError, ValueError):
        return None
    rows = data.get("requests")
    if not isinstance(rows, list):
        return []
    found = []
    for row in rows:
        if not isinstance(row, dict) or row.get("status") != "implemented":
            continue
        number = _number(row.get("id"))
        if number is not None:
            found.append((number, str(row["id"])))
    return [rid for _, rid in sorted(found)]


def _cited(root):
    """Request ids the wiki log already cites."""
    try:
        text = (Path(root) / WIKI_LOG_REL).read_text(encoding="utf-8-sig")
    except OSError:
        return None
    return {f"REQ-{m.group(1)}" for m in REQ_ID.finditer(text)}


def build(root="."):
    """Report implemented requests with no corresponding wiki ingest."""
    root = Path(root)
    blank = {"status": "ok", "uningested": [], "baseline": None,
             "implemented_since_baseline": 0}

    if not (root / WIKI_INDEX_REL).is_file():
        # No wiki is a legitimate state, not a failure to ingest.
        return {**blank, "status": "no_wiki"}

    implemented = _implemented(root)
    cited = _cited(root)
    if implemented is None or cited is None:
        return {**blank, "status": "unreadable"}
    if not implemented:
        return blank

    # Anchor on the HIGHEST cited request - the wiki's high-water mark. The
    # actionable question is "what shipped since the last ingest"; anchoring on
    # the earliest cited request instead surfaced ~70 historical items in this
    # repo and buried the signal. Older gaps are a backfill concern, so they are
    # counted for transparency but kept out of the actionable list.
    cited_numbers = [n for n in (_number(c) for c in cited) if n is not None]
    baseline_number = max(cited_numbers) if cited_numbers else None
    baseline = f"REQ-{baseline_number:03d}" if baseline_number is not None else None

    uningested, historical = [], []
    for rid in implemented:
        if rid in cited:
            continue
        number = _number(rid) or 0
        if baseline_number is None or number >= baseline_number:
            uningested.append(rid)
        else:
            historical.append(rid)

    return {
        "status": "attention" if uningested else "ok",
        "uningested": uningested,
        "baseline": baseline,
        "historical_gap": len(historical),
    }


def main(argv=None):
    parser = argparse.ArgumentParser(
        description="Report implemented requests with no wiki ingest.")
    parser.add_argument("--repo-root", default=".")
    args = parser.parse_args(argv)
    report = build(args.repo_root)
    print(json.dumps(report, indent=2))
    return 0


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