"""Keep the data inside ../widget.html equal to the data in toy.py and evalset.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 evalset import QUESTIONS, UNKNOWN_PHRASES, Z, describe, wobble
from toy import ALSO_SHARED, DONT_KNOW, GUESS, MIN_SHARED, PAGE, STOP

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


def config():
    return {"page": list(PAGE), "stop": sorted(STOP), "guess": GUESS, "dontKnow": DONT_KNOW, "minShared": MIN_SHARED,
            "alsoShared": ALSO_SHARED, "unknown": list(UNKNOWN_PHRASES), "z": Z,
            "wobble": ["".join("1" if flip else "0" for flip in row) for row in wobble()],
            "questions": [{"q": q[0], "right": q[1], "kind": q[2], "args": q[3], "check": describe(q)} for q in QUESTIONS]}


def dump(value):
    return json.dumps(value, ensure_ascii=False)


def embed(html):
    """html with the config block rewritten from toy.py and evalset.py (one key per line, one question per line)."""
    cfg = config()
    lines = [f" {dump(key)}: {dump(value)}" for key, value in cfg.items() if key != "questions"]
    lines.append(' "questions": [\n  ' + ",\n  ".join(dump(q) for q in cfg["questions"]) + "\n ]")
    block = "{\n" + ",\n".join(lines) + "\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 toy.py and evalset.py")
