"""Keep the copy of the model, the card and the chats inside ../widget.html equal to the ones in settings_calc.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 settings_calc as sc

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


def config():
    """What the page needs to run the same server: the model, the card, the drawn chats and the settings it offers."""
    return {
        "params": sc.L24.PARAMS, "bytesPerWeight": sc.L24.FP16_BYTES, "kvBytes": sc.KV_BYTES, "peak": sc.L24.A100_PEAK_FLOPS, "bandwidth": sc.L24.A100_BANDWIDTH,
        "gpuBytes": sc.GPU_BYTES, "weightBytes": sc.WEIGHT_BYTES, "reserveBytes": sc.RESERVE_BYTES, "blockTokens": sc.BLOCK_TOKENS, "blockBytes": sc.BLOCK_BYTES,
        "typical": sc.TYPICAL_CHAT, "longest": sc.LONGEST, "caps": sc.CAPS, "opening": sc.OPENING, "prompts": sc.CHATS["prompts"], "replies": sc.CHATS["replies"],
    }


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