"""Keep the copy of the corpus and the questions 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_lm import load_corpus

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


def embed(html):
    """html with both data blocks rewritten from corpus.txt 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")
    prompts = json.dumps(PROMPTS, ensure_ascii=False, indent=1)
    html = CORPUS_BLOCK.sub(lambda m: m.group(1) + corpus + m.group(3), html, count=1)
    return PROMPTS_BLOCK.sub(lambda m: m.group(1) + "\n" + prompts + "\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 and prompts.py")
