"""Keep the numbers inside ../widget.html equal to kernel_fusion.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 kernel_fusion as kf

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


def widget_data() -> dict:
    return {"side": kf.SIDE, "elem_bytes": kf.FP16_BYTES, "peak_flops": kf.A100_PEAK_FLOPS, "step_flops": kf.A100_STEP_FLOPS, "bandwidth": kf.A100_BANDWIDTH,
            "max_steps": kf.MAX_STEPS}


def embed(html: str) -> str:
    """html with the data block rewritten from kernel_fusion.py."""
    block = json.dumps(widget_data(), indent=1)
    return DATA_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 kernel_fusion.py")
