#!/usr/bin/env python3
"""
Refresh the markup embedded in checkout/payxea-checkout-hosted.js from
checkout/payxea-checkout-hosted.source.html (full outer HTML string: payxea-checkout-host wrapper).

After editing the source fragment, run from repo root:
  python3 tools/build-checkout-js.py
"""
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
SOURCE = ROOT / "checkout" / "payxea-checkout-hosted.source.html"
JS = ROOT / "checkout" / "payxea-checkout-hosted.js"


def main() -> None:
    if not SOURCE.exists():
        raise SystemExit(f"Missing {SOURCE} — add the checkout HTML wrapper first.")
    wrapped = SOURCE.read_text(encoding="utf-8").strip()
    js = JS.read_text(encoding="utf-8")
    assign = "  var PAYXEA_CHECKOUT_HTML = " + json.dumps(wrapped) + ";"
    key = "\n\n  function _mount"
    i = js.find("\n  var PAYXEA_CHECKOUT_HTML = ")
    j = js.find(key, i)
    if i < 0 or j < 0:
        raise SystemExit("Could not find PAYXEA_CHECKOUT_HTML / _mount boundaries")
    js2 = js[:i] + "\n" + assign + key + js[j + len(key) :]
    JS.write_text(js2, encoding="utf-8")
    print("Updated PAYXEA_CHECKOUT_HTML in", JS.relative_to(ROOT))


if __name__ == "__main__":
    main()
