#!/usr/bin/env python3
"""Inline-bundle corpus.html → a single portable file for the public deploy.

The dev/serve version of corpus.html fetches eda_report.json + tokens.json over
HTTP. For deploy (me.nech.pl/parvagues/viz) we want ONE self-contained file with
no fetches and no relative-asset fragility, so we embed the two JSONs into the
empty <script id="eda-data"> / <script id="tok-data"> blocks the page already
reads first (it only falls back to fetch when those are empty).

    python3 build_corpus.py            # → dist/viz.html
    python3 build_corpus.py -o out.html

parsers-over-copy: the source of truth stays corpus.html + the generated JSONs;
this is a pure mechanical bundle step, re-runnable after any `tide_eda.py` run.
"""
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent


def _embed(html: str, script_id: str, payload: str) -> str:
    """Replace the (empty) <script id=...></script> body with JSON payload."""
    open_tag = f'<script id="{script_id}" type="application/json">'
    i = html.find(open_tag)
    if i < 0:
        raise SystemExit(f"corpus.html missing <script id={script_id!r}> block")
    j = html.find("</script>", i)
    # </ inside JSON would break the parser; escape the only dangerous sequence.
    safe = payload.replace("</", "<\\/")
    return html[: i + len(open_tag)] + safe + html[j:]


def build(out: Path) -> Path:
    html = (HERE / "corpus.html").read_text()
    eda = (HERE / "eda_report.json").read_text()
    tok_path = HERE / "tokens.json"
    tok = tok_path.read_text() if tok_path.exists() else "null"
    # minify the JSON a touch (re-dump without the indent)
    eda = json.dumps(json.loads(eda), ensure_ascii=False, separators=(",", ":"))
    tok = json.dumps(json.loads(tok), ensure_ascii=False, separators=(",", ":"))
    html = _embed(html, "eda-data", eda)
    html = _embed(html, "tok-data", tok)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(html)
    return out


def main():
    out = HERE / "dist" / "viz.html"
    args = sys.argv[1:]
    if args and args[0] in ("-o", "--out"):
        out = Path(args[1])
    p = build(out)
    kb = p.stat().st_size / 1024
    print(f"⛵ bundled → {p}  ({kb:.0f} KB, self-contained, no fetch)")
    print(f"   deploy: copy to me.nech.pl/parvagues/viz/index.html")


if __name__ == "__main__":
    main()
