"""Keep the numbers and settings inside ../widget.html equal to the ones in rent_vs_own.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 rent_vs_own as rvo

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 sums: lesson 29's three planner numbers, the sizes of a reply, the month, the chart's box, the values each control offers and the
    opening settings."""
    return {
        "stay": rvo.DESIGN["stay"], "speed": rvo.DESIGN["speed"], "memory": rvo.DESIGN["memory"], "headroom": rvo.HEADROOM, "rate": rvo.REPLIES_PER_GPU_SECOND,
        "tokensIn": rvo.TOKENS_IN, "tokensOut": rvo.TOKENS_OUT, "tokensPerReply": rvo.TOKENS_PER_REPLY, "days": rvo.DAYS, "hoursPerMonth": rvo.HOURS_PER_MONTH,
        "maxGpus": rvo.MAX_GPUS, "box": [rvo.W, rvo.H, rvo.PAD], "maxSteps": rvo.MAX_STEPS,
        "tokensB": rvo.TOKENS_B, "hours": list(rvo.HOURS_RANGE), "people": list(rvo.PEOPLE_RANGE), "pricesIn": rvo.PRICES_IN, "pricesOut": rvo.PRICES_OUT,
        "gpuHours": rvo.GPU_HOURS, "spares": rvo.SPARES, "opening": rvo.OPENING,
    }


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