"""Keep the rows and the settings inside ../widget.html equal to the ones here.

    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 sampler import DRAWS, ROWS, SLACK, WARMUP, as_chances, row_of, toy

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


def config():
    """The rows the page offers, as the toy counted them, and the constants of the draw."""
    model = toy.train(toy.lines_of(toy.load_corpus()))
    rows = []
    for row in ROWS:
        ranked, total = row_of(model, row["context"])
        rows.append({"id": row["id"], "name": row["name"], "ranked": [[token, count] for token, count in ranked], "total": total})
    return {"rows": rows, "draws": DRAWS, "warmup": WARMUP, "slack": SLACK}


def embed(html):
    """html with the data block rewritten from sampler.py and lesson 4's toy."""
    settings = json.dumps(config(), ensure_ascii=False, separators=(", ", ": ")).replace("<", "\\u003c")
    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 sampler.py and lesson 4's toy")
