"""Keep the numbers inside ../widget.html equal to the ones in bill.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

from bill import DAYS_PER_MONTH, EXAMPLE, EXAMPLE_CHATS_PER_DAY, EXAMPLE_KEEP, EXAMPLE_PRICES

WIDGET = Path(__file__).resolve().parent.parent / "widget.html"
CONFIG_BLOCK = re.compile(r'(<script type="application/json" id="bil-config">)(.*?)(</script>)', re.S)
WORDS_PER_100_TOKENS = (60, 80)   # Google's tokens page: "100 tokens is equal to about 60-80 English words"


def config():
    return {"system": EXAMPLE.system, "turns": EXAMPLE.turns, "message": EXAMPLE.message, "reply": EXAMPLE.reply,
            "reasoning": EXAMPLE.reasoning, "chatsPerDay": EXAMPLE_CHATS_PER_DAY, "retryPercent": 0,
            "priceIn": EXAMPLE_PRICES[0], "priceOut": EXAMPLE_PRICES[1], "keep": EXAMPLE_KEEP,
            "daysPerMonth": DAYS_PER_MONTH, "wordsPer100Tokens": list(WORDS_PER_100_TOKENS)}


def embed(html):
    """html with the config block rewritten from bill.py."""
    block = json.dumps(config(), indent=1)
    return CONFIG_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 bill.py")
