"""Install payments.checkout host paths into the existing three Starter runtimes."""
from __future__ import annotations

import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from src.domain.app_blocks.hosts import merge_host_map  # noqa: E402


def main():
    for framework, impls in (
        ("html", {
            "create": "js/checkout-blocks.js#mountCheckoutForm",
            "return": "js/checkout-blocks.js#mountCheckoutReturn",
            "cancel": "js/checkout-blocks.js#mountCheckoutCancel",
            "catalog": "js/checkout-blocks.js#mountCatalogForm",
            "capture": "js/checkout-blocks.js#mountCaptureForm",
            "refund": "js/checkout-blocks.js#mountRefundForm",
        }),
        ("nuxt_app", {
            "create": "components/starter/blocks/CheckoutForm.vue",
            "return": "components/starter/blocks/CheckoutReturn.vue",
            "cancel": "components/starter/blocks/CheckoutCancel.vue",
            "catalog": "components/starter/blocks/CheckoutCatalog.vue",
            "capture": "components/starter/blocks/CheckoutCapture.vue",
            "refund": "components/starter/blocks/CheckoutRefund.vue",
        }),
        ("react_app", {
            "create": "src/components/starter/checkout-blocks.jsx#CheckoutForm",
            "return": "src/components/starter/checkout-blocks.jsx#CheckoutReturn",
            "cancel": "src/components/starter/checkout-blocks.jsx#CheckoutCancel",
            "catalog": "src/components/starter/checkout-blocks.jsx#CheckoutCatalog",
            "capture": "src/components/starter/checkout-blocks.jsx#CheckoutCapture",
            "refund": "src/components/starter/checkout-blocks.jsx#CheckoutRefund",
        }),
    ):
        path = ROOT / "boilerplates" / framework / "p2hs/app-block-hosts.json"
        hosts = merge_host_map(json.loads(path.read_text(encoding="utf-8")))
        for host in hosts["hosts"]:
            if host["block"] == "payments.checkout" and host["slot"] in impls:
                host["implementation"] = impls[host["slot"]]
        hosts["hosts"] = [host for host in hosts["hosts"] if host.get("implementation")]
        mapped = [
            host for host in hosts["hosts"]
            if host["block"] == "payments.checkout" and host["slot"] in impls
        ]
        if len(mapped) != len(impls):
            raise SystemExit(f"unmapped checkout slots for {framework}: {mapped}")
        path.write_text(json.dumps(hosts, indent=2) + "\n", encoding="utf-8")
    print("payments.checkout hosts materialized")


if __name__ == "__main__":
    main()
