#!/usr/bin/env python3
"""Renumber every `Fig N ·` title in an explainer page, in document order.

    python scripts/renumber.py index.html          # rewrites in place
    python scripts/renumber.py index.html --dry    # just report the count

Inserting a figure in the middle invalidates every number after it, and the
prose cross-references ("see Fig 12") go stale silently. The discipline that
keeps this cheap:

  1. While drafting, give new figures a placeholder number out of the real
     range — `Fig 91`, `Fig 92` — so nothing collides mid-edit.
  2. When the figure is in its final position, run this. It renumbers 1..N by
     document order, which is the only order that matters.
  3. Then grep the prose for `Fig ` and fix the cross-references by hand —
     this script deliberately does NOT touch them, because a stale reference is
     a claim about the world and only you know which figure was meant.

Verify after: the numbers must be contiguous from 1 and each must appear
exactly once (see SKILL.md's closing checklist).
"""
import re, sys
from pathlib import Path

PAT = re.compile(r'(fig-title">Fig )(\d+)( ·)')


def renumber(path, dry=False):
    txt = Path(path).read_text()
    n = [0]

    def rep(m):
        n[0] += 1
        return f"{m.group(1)}{n[0]}{m.group(3)}"

    out = PAT.sub(rep, txt)
    if not dry:
        Path(path).write_text(out)
    return n[0]


if __name__ == "__main__":
    if len(sys.argv) < 2:
        sys.exit(__doc__)
    p = sys.argv[1]
    dry = "--dry" in sys.argv
    total = renumber(p, dry)
    print(("would renumber" if dry else "renumbered"), total, "figures in", p)
    nums = [int(m.group(2)) for m in PAT.finditer(Path(p).read_text())]
    gaps = [i + 1 for i, v in enumerate(nums) if v != i + 1]
    print("contiguous 1..N:", not gaps, ("first gap at " + str(gaps[:5])) if gaps else "")
