#!/usr/bin/env python3
"""light-quote.py — the catalog quote, generated, not carried.

The /light/ catalog carries the register's poster numerals as a hand-written
line ("the register — — · — · 4 · 24 · …"). Wake 02:35 built the WALL branch:
verify-descs.py re-derives the sequence and FAILS the build if the hand forgot
to re-quote. This generator closes the derivation arm: it INJECTS the derived
sequence into site/light/index.html at build time, between explicit markers
(<!-- regs-quote:begin --> … <!-- regs-quote:end -->), the way artpage injects
the count line into /art/. The hand never types the sequence again; /light/
becomes the garden's first hybrid surface — hand prose, machine quote.

The markers are the seam, made visible: anything between them is the machine's,
anything outside is the watcher's. If the seam is missing (a wake removed it),
the generator FAILS LOUDLY instead of silently skipping — a seam is a seam.

Usage:
  python3 light-quote.py            # inject the derived quote into /light/
  python3 light-quote.py --check    # exit 1 if the page on disk is stale

The finish script runs this BEFORE verify-descs.py, which keeps its catalog
check as the gate on this generator's output: the wall proves the rendered
page carries the machine's line, mutation-testable exactly as before.
"""

import argparse
import re
import sys
from pathlib import Path

import regpage

TOOLS_DIR = Path(__file__).resolve().parent
SITE_DIR = TOOLS_DIR.parent
OUT = SITE_DIR / "light" / "index.html"

BEGIN = "<!-- regs-quote:begin -->"
END = "<!-- regs-quote:end -->"
MARKER_RE = re.compile(
    re.escape(BEGIN) + r"(.*?)" + re.escape(END), re.S
)


def derived_seq():
    """The one derivation — regpage.catalog_seq() is the single source both
    this generator and verify-descs.py read. The quote cannot be derived two
    ways because there is one way."""
    return regpage.catalog_seq()


def inject(page_text, seq):
    """Replace the content between the markers with the derived sequence.
    Raises if the seam is missing — the generator never writes a page whose
    seam it cannot see."""
    if not MARKER_RE.search(page_text):
        raise SystemExit(
            "light-quote: markers missing in light/index.html — "
            "the seam was removed; restore <!-- regs-quote:begin -->/<!-- regs-quote:end -->"
        )
    return MARKER_RE.sub(BEGIN + seq + END, page_text, count=1)


def build():
    on_disk = OUT.read_text() if OUT.exists() else ""
    return inject(on_disk, derived_seq())


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--check", action="store_true",
                    help="verify the on-disk page carries the derived quote; exit 1 if stale")
    a = ap.parse_args()

    seq = derived_seq()
    on_disk = OUT.read_text() if OUT.exists() else ""
    m = MARKER_RE.search(on_disk)
    if not m:
        raise SystemExit("light-quote: markers missing — restore the seam in light/index.html")

    inside = m.group(1)
    if a.check:
        if inside == seq:
            print(f"light-quote: {OUT.name} current (quote injected: {seq})")
            return
        raise SystemExit(
            f"light-quote: {OUT.name} STALE — derived '{seq}' != carried '{inside}'. "
            f"Run python3 tools/light-quote.py"
        )

    fresh = inject(on_disk, seq)
    OUT.write_text(fresh)
    print(f"light-quote: wrote {OUT.name} — quote injected from regpage.catalog_seq()")


if __name__ == "__main__":
    main()
