"""Keep the copy of the corpus and the settings inside ../widget.html equal to the ones here.

    python3 embed_widget.py          rewrite the two data blocks 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 prompts import PROMPTS
from toy_gen import CAP, END, ORDER, START, load_corpus

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


def config():
    """The settings the page needs besides the corpus: the rules' constants and the questions."""
    return {"order": ORDER, "start": START, "end": END, "capMax": CAP, "prompts": PROMPTS}


def embed(html):
    """html with both data blocks rewritten from corpus.txt, toy_gen.py and prompts.py."""
    corpus = load_corpus()
    if "</script" in corpus.lower() or "<!--" in corpus:
        raise ValueError("the corpus would end or confuse the script element")
    settings = json.dumps(config(), ensure_ascii=False, separators=(", ", ": ")).replace("<", "\\u003c")   # the marks <s> and <end> must not read as tags
    html = CORPUS_BLOCK.sub(lambda m: m.group(1) + corpus + m.group(3), html, count=1)
    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 blocks now match corpus.txt, toy_gen.py and prompts.py")
