#!/usr/bin/env python3
"""Assemble the delivery-arc page: tpl + inlined GSAP + scene manifests + base64 heroes.

Heroes are inlined ONCE (in the <img> src); the slice engine reuses img.src for the
slab backgrounds, so nothing is duplicated. Manifests come from tools/slice-arc.py.
"""
import base64, json, pathlib, re

ROOT = pathlib.Path(__file__).resolve().parent.parent

def b64(webp):
    return "data:image/webp;base64," + base64.b64encode((ROOT / "assets/dist" / webp).read_bytes()).decode()

def man(tag):
    return json.dumps(json.loads((ROOT / "pilot" / f"manifest-{tag}.json").read_text()),
                      separators=(",", ":"))

out = (ROOT / "pilot/arc.tpl.html").read_text() \
    .replace("__MAN_DOCKER__", man("docker")) \
    .replace("__MAN_CLUSTER__", man("cluster")) \
    .replace("__MAN_GITOPS__", man("gitops")) \
    .replace("__MAN_SUPPLY__", man("supply")) \
    .replace("__MAN_HELM__", man("helm")) \
    .replace("__HERO_DOCKER__", b64("docker-layers.webp")) \
    .replace("__HERO_CLUSTER__", b64("course-II-cluster.webp")) \
    .replace("__HERO_GITOPS__", b64("course-VI-gitops.webp")) \
    .replace("__HERO_SUPPLY__", b64("course-VII-supply-chain.webp")) \
    .replace("__HERO_HELM__", b64("course-VIII-helm-press.webp")) \
    .replace("__HERO_APPENDIX__", b64("appendix-dependency-ledger.webp")) \
    .replace("__DIAG_FLOW__", "data:image/svg+xml;base64," + base64.b64encode((ROOT / "assets/dist/delivery-flow.svg").read_bytes()).decode())

assert "__MAN_" not in out and "__HERO_" not in out and "__DIAG_" not in out, "unfilled placeholder"

out = (f"<script>{(ROOT / 'gsap.min.js').read_text()}</script>\n"
       f"<script>{(ROOT / 'st.min.js').read_text()}</script>\n" + out)

dest = ROOT / "pilot/arc.html"
dest.write_text(out)
heroes = len(re.findall(r"data:image/webp", out))
print(f"built pilot/arc.html  {len(out)/1024:.0f}KB  ({heroes} heroes inlined)")
