"""Keep the copy of the demo files inside ../widget.html equal to the ones modelfile.py builds.

    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)

The data block holds the two demo files as hexadecimal text. The page shows what is in them and runs nothing.
"""
import json
import re
import sys
from pathlib import Path

import harmless
import modelfile as mf

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


def config():
    """What the page needs: the bytes of both demo files, the name and note of the one function, and the restricted loader's list."""
    return {"pickle": mf.demo_pickle().hex(), "safetensors": mf.demo_safetensors().hex(), "func": harmless.ran_on_open.__name__, "note": mf.NOTE,
            "allowed": [f"{m}.{n}" for m, n in mf.ALLOWED]}


def embed(html):
    """html with the data block rewritten from modelfile.py."""
    settings = json.dumps(config(), ensure_ascii=False, separators=(", ", ": "))
    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 modelfile.py")
