"""Keep the data inside ../widget.html equal to the data in leak_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 leak_sim import EXPERIMENTS, GUESSES, QUESTIONS, RIGHT, SEQUENCE, TRIES, USERS, percent, simulate, timing

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


def config():
    shared, salted = timing(False), timing(True)
    average = {"shared": [round(w) for w in shared["average"]], "salted": [round(w) for w in salted["average"]]}
    return {"users": [{"name": u.name, "order": u.order, "street": u.street} for u in USERS],
            "questions": [{"q": q, "a": a} for q, a in QUESTIONS],
            "sequence": [list(r) for r in SEQUENCE],
            "opening": next(s.n for s in simulate(False) if s.leak),
            "guesses": GUESSES, "right": RIGHT, "tries": TRIES, "runs": EXPERIMENTS, "chance": percent(1, len(GUESSES)),
            "axis": -(-max(max(v) for v in average.values()) // 10) * 10,
            "timing": {"shared": {"average": average["shared"], "one": shared["one"], "many": shared["many"]},
                       "salted": {"average": average["salted"], "one": salted["one"], "many": salted["many"]}}}


def embed(html):
    """html with the config block rewritten from leak_sim.py."""
    block = json.dumps(config())
    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 leak_sim.py")
