"""Keep the copy of the model, the chip and the 2,000 invented requests inside ../widget.html equal to the ones in tail_sim.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 tail_sim as sim

WIDGET = Path(__file__).resolve().parent.parent / "widget.html"
CONFIG_BLOCK = re.compile(r'(<script type="application/json" id="tl-config">)(.*?)(</script>)', re.S)
OPENING = {"rate": sim.OPENING_RATE, "measure": "total"}


def config():
    """What the page needs to run the same toy server and tester: the model, the chip, the drawn requests and the settings it offers."""
    b = sim.batching
    return {
        "params": b.PARAMS, "bytesPerWeight": b.FP16_BYTES, "kvBytes": b.KV_BYTES_PER_TOKEN, "peak": b.A100_PEAK_FLOPS, "bandwidth": b.A100_BANDWIDTH,
        "slots": sim.SLOTS, "gaps": sim.WORKLOAD["gaps"], "prompts": sim.WORKLOAD["prompts"], "replies": sim.WORKLOAD["replies"],
        "rates": sim.RATES, "capacity": round(sim.capacity(), 1), "connections": sim.CONNECTIONS, "pauseAt": sim.PAUSE_AT, "pause": sim.PAUSE,
        "rerolls": sim.REROLLS, "opening": OPENING,
    }


def embed(html):
    """html with the data block rewritten from tail_sim.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 tail_sim.py")
