"""Keep the copy of the tokenizer, the rules and the example texts inside ../widget.html equal to the ones in prefix_cache.py.

    python3 embed_widget.py          rewrite the data block in widget.html
    python3 embed_widget.py --check  exit 1 if widget.html differs (test_widget.py runs the same check)
"""
import json
import re
import sys
from pathlib import Path

import prefix_cache as sim

WIDGET = Path(__file__).resolve().parent.parent / "widget.html"
CONFIG_BLOCK = re.compile(r'(<script type="application/json" id="pcw-config">)(.*?)(</script>)', re.S)


def config():
    """What the page needs to run the same match and the same sums: lesson 1's learned merges, the four rules, the settings and the texts."""
    return {
        "merges": [list(pair) for pair in sim.merges()], "marker": sim.MARKER, "docBase": sim.DOC_BASE,
        "rules": [{"key": r.key, "summary": sim.summary(r), "price": float(r.price), "write": float(r.write), "read": float(r.read),
                   "minimum": r.minimum, "lifetime": r.lifetime} for r in sim.RULES],
        "docs": sim.DOC_LENGTHS, "defaultDoc": sim.DEFAULT_DOC, "ages": sim.AGES, "defaultAge": sim.DEFAULT_AGE,
        "earlier": sim.EARLIER, "presets": sim.PRESETS,
    }


def embed(html):
    """html with the data block rewritten from prefix_cache.py."""
    settings = json.dumps(config(), ensure_ascii=False, separators=(", ", ": "))
    return CONFIG_BLOCK.sub(lambda m: m.group(1) + "\n" + settings + "\n" + m.group(3), html, count=1)


if __name__ == "__main__":
    current = WIDGET.read_text(encoding="utf-8")
    updated = embed(current)
    if "--check" in sys.argv:
        sys.exit(0 if updated == current else 1)
    WIDGET.write_text(updated, encoding="utf-8")
    print("widget.html data block now matches prefix_cache.py")
