"""Keep the tables, limits and settings inside ../widget.html equal to the ones in capacity_plan.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

import capacity_plan as cp

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


def config():
    """What the page needs to repeat the plan: for each chat mix its table of one GPU, its memory limit, its replies per user and its words, the targets the slider offers and the opening settings."""
    return {
        "headroom": cp.HEADROOM, "targets": cp.TARGETS, "opening": cp.OPENING, "mixOrder": list(cp.MIXES),
        "mixes": {mix: {"label": m["label"], "prompts": list(m["prompts"]), "replies": list(m["replies"]), "each": m["each"], "memory": cp.memory_limit(mix),
                         "table": cp.step_table(mix)}
                  for mix, m in cp.MIXES.items()},
    }


def embed(html):
    """html with the data block rewritten from capacity_plan.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 capacity_plan.py")
