#!/usr/bin/env python3
"""Inject the dictation frame into hairstylist-form-full-prototype.html.

The prototype is standalone by design — you open the file and it works, no
folder, no server. That means the extractor has to be inlined, and an inlined
copy is exactly the drift that hid three bugs in this project already (HANDOFF
§8). So it is GENERATED, never hand-edited: this script rewrites the block
between the markers from dictation/extract.js, and `--check` fails if the two
have diverged.

    python3 dictation/build-into-prototype.py          # regenerate
    python3 dictation/build-into-prototype.py --check   # CI: are they in sync?

Every class is prefixed `dct-`; the form already has its own `.chip`.
"""
import re, sys, pathlib

ROOT = pathlib.Path(__file__).resolve().parent.parent
PROTO = ROOT / "hairstylist-form-full-prototype.html"
EXTRACT = ROOT / "dictation" / "extract.js"

OPEN = "/* ==== GENERATED from dictation/extract.js — do not edit here ==== */"
CLOSE = "/* ==== END GENERATED ==== */"


def payload() -> str:
    src = EXTRACT.read_text(encoding="utf-8")
    return f"{OPEN}\n{src.rstrip()}\n{CLOSE}"


def main() -> int:
    check = "--check" in sys.argv
    html = PROTO.read_text(encoding="utf-8")

    if OPEN not in html:
        print("markers not found — the frame has not been injected yet", file=sys.stderr)
        return 2

    block = re.compile(re.escape(OPEN) + r".*?" + re.escape(CLOSE), re.S)
    want = payload()
    have = block.search(html).group(0)

    if have == want:
        print("in sync: prototype carries the current extract.js")
        return 0
    if check:
        print("OUT OF SYNC: the prototype's inlined extractor differs from "
              "dictation/extract.js. Run this script without --check.", file=sys.stderr)
        return 1

    PROTO.write_text(block.sub(lambda _: want, html, count=1), encoding="utf-8")
    print(f"regenerated: {len(want)} chars inlined from extract.js")
    return 0


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