"""Keep the data inside ../widget.html equal to the data in 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

from sim import BASE, CAP, CLIENTS, FIXED, LIMIT, RULES, SEED, TRIES

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


def config():
    return {"clients": CLIENTS, "limit": LIMIT, "tries": TRIES, "fixed": FIXED, "base": BASE, "cap": CAP, "seed": SEED,
            "rules": [{"id": i, "name": name} for i, name in RULES]}


def embed(html):
    """html with the config block rewritten from sim.py."""
    block = "{\n" + ",\n".join(f" {json.dumps(key)}: {json.dumps(value)}" for key, value in config().items()) + "\n}"
    return CONFIG_BLOCK.sub(lambda m: m.group(1) + "\n" + block + "\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 sim.py")
