#!/usr/bin/env python3
"""Generates every course figure as an SVG into ../assets/.

Run:  python3 tools/make_diagrams.py
"""

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from diagram_kit import (  # noqa: E402
    Diagram, INK, MUTED, LINE, PANEL, SOFT, NAVY, TEAL, AMBER, PLUM, SLATE,
    T_NAVY, T_TEAL, T_AMBER, T_TONE,
    hchain, vchain, wrap,
)

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "assets")
os.makedirs(OUT, exist_ok=True)
BUILT = []


def emit(dg, name):
    path = os.path.join(OUT, name + ".svg")
    dg.save(path)
    BUILT.append(name)
    return path


# ============================================================ Lesson 0

def map_of_voltville():
    d = Diagram(900, 712, "How a utility works, top to bottom")
    cx = 290
    nx = 470  # notes column

    d.box(cx - 135, 22, 270, 42, [("GENERATION / PROCUREMENT", 13, "bold")], "navy")
    d.arrow(cx, 66, cx, 90)

    d.box(cx - 185, 92, 370, 48, [("THE GRID", 14, "bold")], "slate")
    d.note(nx + 20, 121, "physical assets — poles, pipes, substations")
    d.arrow(cx, 142, cx, 166)

    d.box(cx - 150, 168, 300, 44, [("CONNECTION OBJECT", 13, "bold")], "teal")
    d.note(nx, 195, "the building's link to the grid")
    d.arrow(cx, 214, cx, 238)

    d.box(cx - 115, 240, 230, 50,
          [("Lindenstraße 12", 14, "bold"), ("the building", 11)], "plain")
    d.note(nx, 270, "one building, many flats")

    # premises
    for x in (130, 290, 450):
        d.elbow(cx, 292, x, 338)
    for x, lbl in ((130, "flat 3A"), (290, "flat 3B"), (450, "flat 3C")):
        kind = "soft" if lbl != "flat 3B" else "plain"
        d.box(x - 55, 340, 110, 40, [(lbl, 12.5, "bold")], kind)
    d.note(530, 365, "PREMISES — the usage units")

    d.arrow(cx, 382, cx, 410)
    d.box(cx - 140, 412, 280, 50,
          [("Frau Meyer", 14, "bold"), ("the customer", 11)], "navy")
    d.note(nx, 442, "BUSINESS PARTNER — the person")
    d.arrow(cx, 464, cx, 490)

    d.box(cx - 120, 492, 240, 50,
          [("the meter", 13.5, "bold"), ("serial 04127", 11)], "plain")
    d.note(nx, 522, "DEVICE, with REGISTERS")
    d.arrow(cx, 544, cx, 570)

    d.box(cx - 95, 572, 190, 38, [("consumption", 12.5, "bold")], "soft")
    d.arrow(cx, 612, cx, 638)

    d.box(cx - 115, 640, 230, 48, [("THE BILL", 14, "bold")], "amber")
    d.arrow(cx + 118, 664, 468, 664)
    d.box(470, 640, 250, 48,
          [("the money", 13.5, "bold"), ("FI-CA", 11)], "teal")

    d.caption(450, 706,
              "physical world  →  measurement  →  contract  →  money")
    emit(d, "map_of_voltville")


# ============================================================ Lesson 1

def isu_in_erp():
    d = Diagram(880, 330, "IS-U sits inside SAP ERP")
    d.box(30, 24, 820, 274, [], "plain")
    d.text(50, 50, "SAP ERP  /  S/4HANA", size=14, color=INK, anchor="start",
           weight="bold")
    d.note(50, 70, "the standard core")

    mods = ["FI", "CO", "MM", "PM", "HR", "SD"]
    for i, m in enumerate(mods):
        d.box(52 + i * 92, 84, 78, 40, [(m, 13, "bold")], "soft")
    d.note(52 + len(mods) * 92 + 6, 109, "…")

    d.box(52, 146, 776, 130, [], "soft")
    d.text(72, 174, "IS-U layer", size=13.5, color=T_TEAL, anchor="start",
           weight="bold")
    d.note(72, 193, "the utilities extension")

    chips = ["Customers", "Devices", "Meter data", "Energy data",
             "Billing", "FI-CA"]
    for i, c in enumerate(chips):
        d.box(74 + i * 126, 210, 112, 42, [(c, 12, "bold")], "teal")
    emit(d, "isu_in_erp")


def six_pillars():
    d = Diagram(900, 470, "The six functional pillars of IS-U")
    top = [
        [("1. CUSTOMER (CIS)", 12.5, "bold"), ("who they are,", 11),
         ("what they contracted", 11)],
        [("2. DEVICE MANAGEMENT", 12.5, "bold"), ("the hardware in the", 11),
         ("field, and its life", 11)],
        [("3. METER DATA (MDM)", 12.5, "bold"), ("readings in, validated,", 11),
         ("estimated", 11)],
    ]
    for i, lines in enumerate(top):
        d.box(40 + i * 285, 26, 260, 92, lines, "plain")
        d.line(40 + i * 285 + 130, 118, 40 + i * 285 + 130, 148)
    d.line(170, 148, 740, 148)
    d.arrow(450, 148, 450, 178)

    d.box(275, 180, 350, 74,
          [("4. BILLING & INVOICING", 13.5, "bold"),
           ("quantity  ×  rate  =  money", 12)], "amber")
    d.arrow(450, 254, 450, 284)
    d.line(240, 284, 660, 284)
    d.line(240, 284, 240, 306)
    d.line(660, 284, 660, 306)

    d.box(110, 308, 260, 92,
          [("5. FI-CA", 12.5, "bold"), ("receivables, payments,", 11),
           ("dunning, collections", 11)], "navy")
    d.box(530, 308, 260, 92,
          [("6. ENERGY DATA (EDM)", 12.5, "bold"),
           ("interval / profile data,", 11),
           ("settlement, large customers", 11)], "teal")

    d.caption(450, 440,
              "Around them: Customer Service · Reporting · Integration · Compliance")
    emit(d, "six_pillars")


# ============================================================ Lesson 2

def architecture_layers():
    d = Diagram(900, 560, "The three layers of IS-U")

    d.box(30, 24, 840, 92, [], "soft")
    d.text(50, 50, "LAYER 3 — INTERACTION", size=12, color=T_TEAL,
           anchor="start", weight="bold")
    for i, c in enumerate(["SAP GUI", "Fiori launchpad", "CRM / customer\nengagement",
                           "Self-service portal", "Mobile field app"]):
        first, _, second = c.partition("\n")
        lines = [(first, 11, "bold")] + ([(second, 10)] if second else [])
        d.box(50 + i * 162, 62, 150, 40, lines, "plain")

    d.box(30, 128, 840, 214, [], "plain")
    d.text(50, 154, "LAYER 2 — IS-U APPLICATION", size=12, color=T_NAVY,
           anchor="start", weight="bold")
    cols = [
        ("Master data", ["Business Partner", "Contract Account", "Contract",
                         "Installation", "Premise", "Conn. Object",
                         "Device / Register"]),
        ("Processes", ["Move-in / move-out", "Meter reading", "Billing run",
                       "Invoicing run", "Device install", "Disconnection",
                       "Market comms (IDE)"]),
        ("Money", ["FI-CA", "Billing", "Invoicing", "Payments", "Dunning",
                   "Instalments", "Write-off"]),
    ]
    for i, (head, items) in enumerate(cols):
        x = 52 + i * 272
        d.box(x, 172, 254, 156, [], "soft")
        d.text(x + 14, 194, head, size=11.5, color=T_TEAL, anchor="start",
               weight="bold")
        for j, it in enumerate(items):
            d.note(x + 14, 214 + j * 16, "· " + it)

    d.box(30, 354, 840, 84, [], "soft")
    d.text(50, 380, "LAYER 1 — SAP ERP CORE + DATABASE", size=12, color=T_NAVY,
           anchor="start", weight="bold")
    d.note(50, 400, "FI · CO · MM · PM · HR · Basis · authorisations")
    d.note(50, 420, "Database: Oracle / DB2 / MaxDB on ECC  →  SAP HANA on S/4HANA")

    d.arrow(230, 470, 230, 442)
    d.box(80, 472, 300, 62,
          [("AMI / smart-meter head-end, MDUS", 11.5, "bold"),
           ("readings in", 10.5)], "ghost")
    d.arrow(670, 470, 670, 442)
    d.box(520, 472, 300, 62,
          [("Market partners (grid, suppliers)", 11.5, "bold"),
           ("IDoc / EDIFACT", 10.5)], "ghost")
    emit(d, "architecture_layers")


def mass_activity():
    d = Diagram(900, 300, "How a mass activity runs")
    hchain(d, 60, 40, [
        [("SELECT", 12.5, "bold"), ("the population", 11),
         ("\"all contracts in portion 07", 10), ("due on 01.09\"", 10)],
        [("SPLIT", 12.5, "bold"), ("into intervals", 11),
         ("partition by key", 10)],
    ], 230, 100, gap=40, kind=["navy", "teal"])

    for i in range(3):
        d.box(600, 24 + i * 56, 230, 44,
              [(f"job {i+1}  ·  interval {chr(65+i)}", 11.5, "bold")], "soft")
        d.arrow(570, 110, 596, 46 + i * 56)
    d.note(600, 210, "…run in parallel")

    d.arrow(715, 196, 715, 224)
    d.box(560, 226, 310, 54,
          [("RESULTS  +  EXCEPTIONS", 12, "bold"),
           ("failures are parked, not fatal", 10.5)], "amber")
    d.caption(300, 250, "A failed record never stops the run.")
    emit(d, "mass_activity")


# ============================================================ Lesson 3

def master_data_chain():
    d = Diagram(940, 660, "The IS-U master data chain")
    lx, rx = 235, 690

    d.text(235, 30, "COMMERCIAL SIDE", size=12, color=T_NAVY, weight="bold")
    d.caption(235, 48, "who, and money")
    d.text(690, 30, "TECHNICAL SIDE", size=12, color=T_TEAL, weight="bold")
    d.caption(690, 48, "where, and hardware")
    d.line(462, 22, 462, 636, color=LINE, dash="4 5")

    # commercial column
    d.box(lx - 145, 66, 290, 60,
          [("BUSINESS PARTNER", 13, "bold"), ("Frau Meyer — the person", 11)],
          "navy")
    d.note(lx - 145, 148, "1 : n", color=MUTED)
    d.arrow(lx, 128, lx, 168)
    d.box(lx - 145, 170, 290, 60,
          [("CONTRACT ACCOUNT", 13, "bold"),
           ("payment method, dunning, cycle", 11)], "navy")
    d.note(lx - 145, 252, "1 : n")
    d.arrow(lx, 232, lx, 272)
    d.box(lx - 145, 274, 290, 66,
          [("CONTRACT", 13, "bold"), ("move-in / move-out dates", 11)], "navy")

    # the hinge
    d.arrow(lx + 150, 307, rx - 156, 307)
    d.arrow(rx - 152, 307, lx + 146, 307)
    d.caption(462, 296, "1 : 1 at a time")

    d.text(rx, 262, "★  THE HINGE", size=11.5, color=T_AMBER, weight="bold")
    d.box(rx - 150, 270, 300, 74,
          [("INSTALLATION", 13.5, "bold"),
           ("division · rate category · facts", 11),
           ("survives every tenant", 11)], "amber")

    d.note(rx - 150, 362, "n : 1")
    d.arrow(rx, 342, rx, 382)
    d.box(rx - 150, 384, 300, 58,
          [("PREMISE", 13, "bold"), ("flat 3B — the usage unit", 11)], "teal")
    d.note(rx - 150, 464, "n : 1")
    d.arrow(rx, 444, rx, 484)
    d.box(rx - 150, 486, 300, 58,
          [("CONNECTION OBJECT", 13, "bold"),
           ("Lindenstraße 12 — the building", 11)], "teal")
    d.arrow(rx, 546, rx, 578)
    d.box(rx - 150, 580, 300, 58,
          [("DEVICE LOCATION + DEVICE", 12.5, "bold"),
           ("\"cellar, left\" · meter 04127 · registers", 10.5)], "plain")

    d.caption(235, 420, "Tenants change these three.")
    d.caption(235, 440, "Buildings change the other three.")
    d.caption(235, 470, "Almost nothing changes both.")
    emit(d, "master_data_chain")


def frau_meyer_objects():
    d = Diagram(900, 400, "What a move-in actually creates")
    d.band(24, 18, 840, 168, "already existed — created when the building was built")
    d.box(48, 48, 250, 44, [("Lindenstraße 12", 12.5, "bold"),
                            ("connection object", 10.5)], "plain")
    d.arrow(298, 70, 326, 70)
    d.box(328, 48, 200, 44, [("flat 3B", 12.5, "bold"), ("premise", 10.5)],
          "plain")
    d.arrow(528, 70, 556, 70)
    d.box(558, 34, 280, 34, [("electricity installation", 11.5, "bold")], "soft")
    d.box(558, 76, 280, 34, [("gas installation", 11.5, "bold")], "soft")
    d.box(558, 126, 280, 40, [("meter 04127 + registers", 11.5, "bold")],
          "plain")
    d.line(698, 110, 698, 126, color=LINE)

    d.band(24, 202, 840, 168, "created today, because someone moved in")
    d.box(48, 232, 250, 46, [("Frau Meyer", 12.5, "bold"),
                             ("business partner", 10.5)], "navy")
    d.arrow(298, 255, 326, 255)
    d.box(328, 232, 200, 46, [("account 8000123456", 11.5, "bold"),
                              ("contract account", 10.5)], "navy")
    d.arrow(528, 255, 556, 255)
    d.box(558, 222, 280, 34, [("contract → electricity", 11.5, "bold")], "navy")
    d.box(558, 264, 280, 34, [("contract → gas", 11.5, "bold")], "navy")
    d.caption(450, 336,
              "Three object types created. The rest outlive her tenancy by decades.")
    emit(d, "frau_meyer_objects")


# ============================================================ Lesson 4

def mr_lifecycle():
    d = Diagram(900, 260, "The meter reading lifecycle")
    stages = [
        [("1. ORDER", 12, "bold"), ("system creates", 10.5),
         ("reading orders", 10.5), ("per schedule", 10.5)],
        [("2. CAPTURE", 12, "bold"), ("meter reader,", 10.5),
         ("customer or", 10.5), ("smart meter", 10.5)],
        [("3. UPLOAD", 12, "bold"), ("result lands on", 10.5),
         ("the register", 10.5), ("in IS-U", 10.5)],
        [("4. VALIDATE", 12, "bold"), ("plausibility;", 10.5),
         ("pass, correct", 10.5), ("or estimate", 10.5)],
        [("5. RELEASE", 12, "bold"), ("reading becomes", 10.5),
         ("billing-relevant;", 10.5), ("billing can run", 10.5)],
    ]
    hchain(d, 40, 26, stages, 148, 116, gap=26,
           kind=["navy", "plain", "plain", "amber", "teal"])
    d.caption(450, 206,
              "A reading is not a number — it is a dated, reasoned, validated event on a register.")
    emit(d, "mr_lifecycle")


def ami_chain():
    d = Diagram(900, 260, "How smart meter data reaches IS-U")
    hchain(d, 40, 26, [
        [("meters", 12.5, "bold"), ("15-minute values", 10.5)],
        [("comms network", 12, "bold"), ("LTE / PLC / mesh", 10.5)],
        [("HEAD-END SYSTEM", 11.5, "bold"), ("speaks the meter", 10.5),
         ("protocol; sends", 10.5), ("commands", 10.5)],
        [("MDM / MDUS layer", 11.5, "bold"), ("validation,", 10.5),
         ("estimation,", 10.5), ("editing (VEE)", 10.5)],
        [("IS-U", 12.5, "bold"), ("billing-relevant", 10.5),
         ("values only", 10.5)],
    ], 148, 106, gap=26, kind=["plain", "soft", "slate", "teal", "navy"])
    d.caption(450, 196,
              "Don't push 14 billion raw values into your billing system — validate and condense first.")
    emit(d, "ami_chain")


# ============================================================ Lesson 5

def bakery_profile():
    """Single-series load profile. One hue, recessive grid, peak direct-labelled."""
    d = Diagram(900, 400, "Bäckerei Grunewald — consumption by hour of day")
    vals = [2.1, 2.0, 2.2, 3.4, 38.4, 41.7, 39.2, 28.5, 24.1, 22.6, 20.3,
            18.7, 16.2, 12.4, 9.8, 8.1, 6.4, 5.2, 4.1, 3.2, 2.8, 2.5, 2.3, 2.1]
    x0, y0, plot_w, plot_h = 74, 68, 780, 250
    ymax = 45

    d.text(74, 30, "Bäckerei Grunewald — consumption by hour of day",
           size=13.5, color=INK, anchor="start", weight="bold")
    d.note(74, 50, "kWh per hour, typical weekday")

    for g in range(0, ymax + 1, 15):
        gy = y0 + plot_h - g / ymax * plot_h
        d.line(x0, gy, x0 + plot_w, gy, color=LINE, sw=1)
        d.text(x0 - 10, gy + 4, str(g), size=10.5, color=MUTED, anchor="end")
    d.text(x0 - 10, y0 - 12, "kWh", size=10.5, color=MUTED, anchor="end")

    slot = plot_w / len(vals)
    bw = slot - 4  # 2px surface gap either side
    for i, v in enumerate(vals):
        bh = v / ymax * plot_h
        bx = x0 + i * slot + 2
        by = y0 + plot_h - bh
        r = min(4, bh / 2)
        # rounded top, square base on the axis
        d.raw(f'<path d="M{bx:.1f},{by + bh:.1f} L{bx:.1f},{by + r:.1f} '
              f'Q{bx:.1f},{by:.1f} {bx + r:.1f},{by:.1f} '
              f'L{bx + bw - r:.1f},{by:.1f} '
              f'Q{bx + bw:.1f},{by:.1f} {bx + bw:.1f},{by + r:.1f} '
              f'L{bx + bw:.1f},{by + bh:.1f} Z" fill="{TEAL}"/>')
        if i % 3 == 0:
            d.text(bx + bw / 2, y0 + plot_h + 18, f"{i:02d}", size=10,
                   color=MUTED)
    d.line(x0, y0 + plot_h, x0 + plot_w, y0 + plot_h, color=MUTED, sw=1.2)
    d.text(x0 + plot_w, y0 + plot_h + 36, "hour of day", size=10.5,
           color=MUTED, anchor="end")

    peak_x = x0 + 5 * slot + slot / 2
    peak_y = y0 + plot_h - 41.7 / ymax * plot_h
    d.text(peak_x + 14, peak_y - 8, "41.7 kWh — the ovens", size=11.5,
           color=INK, anchor="start", weight="bold")
    d.line(peak_x, peak_y - 22, peak_x + 10, peak_y - 12, color=MUTED, sw=1.2)

    d.box(74, 344, 780, 42,
          [("Modest total energy, enormous peak — which is exactly what a demand charge prices.",
            11.5, "bold")], "soft")
    emit(d, "bakery_profile")


def rtp_interface():
    d = Diagram(900, 200, "How interval data reaches billing")
    hchain(d, 40, 60, [
        [("EDM profile values", 12, "bold"), ("the shape", 10.5)],
        [("RTP interface", 12, "bold"), ("aggregates and", 10.5),
         ("prices intervals", 10.5)],
        [("billing engine", 12, "bold"), ("rate & prices", 10.5)],
        [("billing document", 12, "bold")],
    ], 168, 84, gap=30, kind=["teal", "amber", "navy", "plain"])
    d.caption(450, 174,
              "For a household on a flat tariff none of this runs. For Grunewald it is the whole bill.")
    emit(d, "rtp_interface")


# ============================================================ Lesson 6

def device_model():
    d = Diagram(900, 500, "The device data model")
    cx = 300
    d.box(cx - 160, 24, 320, 52,
          [("MATERIAL (MM)", 12.5, "bold"),
           ("\"electricity meter, type X, 3-phase\"", 10.5)], "soft")
    d.note(cx + 175, 54, "a product you can buy and stock")
    d.arrow(cx, 78, cx, 102)

    d.box(cx - 160, 104, 320, 52,
          [("DEVICE CATEGORY", 12.5, "bold"),
           ("registers · units · digits · class", 10.5)], "slate")
    d.note(cx + 175, 134, "the template")
    d.arrow(cx, 158, cx, 182)

    d.box(cx - 160, 184, 320, 56,
          [("DEVICE  (an equipment)", 12.5, "bold"),
           ("serial 04127 — one physical object", 10.5)], "navy")
    d.note(cx + 175, 214, "with a lifecycle and a location")

    for i, r in enumerate(["register 001  ·  total kWh",
                           "register 002  ·  night kWh",
                           "register 003  ·  peak demand kW"]):
        d.box(cx - 100, 268 + i * 44, 380, 36, [(r, 11.5, "bold")], "plain")
        d.line(cx - 130, 240, cx - 130, 286 + i * 44, color=LINE)
        d.line(cx - 130, 286 + i * 44, cx - 100, 286 + i * 44, color=LINE)
    d.note(cx + 292, 312, "the counters")

    d.arrow(cx, 406, cx, 430)
    d.box(cx - 200, 432, 400, 48,
          [("DEVICE LOCATION → PREMISE → CONNECTION OBJECT", 11.5, "bold"),
           ("\"cellar, left\"  ·  flat 3B  ·  Lindenstraße 12", 10.5)], "teal")
    emit(d, "device_model")


def replacement_timeline():
    d = Diagram(900, 260, "A device replacement must chain the readings")
    y = 110
    d.line(70, y, 830, y, color=LINE, sw=2)
    d.line(450, 46, 450, 178, color=AMBER, sw=2, dash="5 4")
    d.text(450, 36, "removal date  ·  14.03", size=11.5, color=T_AMBER,
           weight="bold")

    d.box(80, y - 34, 320, 68,
          [("OLD METER", 12, "bold"), ("final reading  41,274", 11.5)],
          "slate")
    d.box(500, y - 34, 320, 68,
          [("NEW METER", 12, "bold"), ("initial reading  00,000", 11.5)],
          "navy")
    d.arrow(404, y, 446, y)
    d.arrow(454, y, 496, y)

    d.caption(450, 202, "same instant — consumption must be continuous across the swap")
    d.box(80, 216, 740, 34,
          [("Swap those two numbers and you have booked a wrong bill with a delayed fuse.",
            11.5, "bold")], "soft")
    emit(d, "replacement_timeline")


def field_service_chain():
    d = Diagram(900, 560, "From a fault report to a settled cost")
    cx = 450
    steps = [
        ([("Customer or system detects a problem", 12, "bold")], "plain"),
        ([("SERVICE NOTIFICATION", 12.5, "bold"),
          ("what's wrong, where, who reported it", 10.5)], "amber"),
        ([("SERVICE / MAINTENANCE ORDER", 12.5, "bold"),
          ("operations, materials, skills, duration", 10.5)], "navy"),
        ([("SCHEDULING / DISPATCH", 12.5, "bold"),
          ("who, when, in what order", 10.5)], "plain"),
        ([("MOBILE EXECUTION", 12.5, "bold"),
          ("work done · readings · photos · materials", 10.5)], "teal"),
    ]
    y = 26
    for lines, kind in steps:
        d.box(cx - 210, y, 420, 54, lines, kind)
        y += 54
        if y < 300:
            d.arrow(cx, y + 2, cx, y + 24)
            y += 26
    d.arrow(cx, y + 2, cx, y + 30)
    d.line(230, y + 30, 670, y + 30, color=MUTED)
    d.line(230, y + 30, 230, y + 48, color=MUTED)
    d.line(670, y + 30, 670, y + 48, color=MUTED)

    d.box(70, y + 50, 320, 62,
          [("DEVICE RECORD UPDATED", 12, "bold"),
           ("install / remove / replace,", 10.5), ("readings captured", 10.5)],
          "slate")
    d.box(510, y + 50, 320, 62,
          [("COSTS SETTLED IN CO", 12, "bold"),
           ("labour + materials to the right", 10.5),
           ("cost object; chargeable work → next bill", 10.5)], "plum")
    emit(d, "field_service_chain")


def device_lifecycle():
    d = Diagram(900, 300, "A meter's life across systems")
    top = ["procure (MM)", "goods receipt", "stock", "issue to technician",
           "INSTALL (IS-U)"]
    bot = ["REMOVE (IS-U)", "return to stock", "test", "refurbish", "scrap"]
    for i, t in enumerate(top):
        kind = "navy" if "IS-U" in t else "plain"
        d.box(24 + i * 176, 40, 156, 46, [(t, 11.5, "bold")], kind)
        if i < len(top) - 1:
            d.arrow(24 + i * 176 + 158, 63, 24 + (i + 1) * 176 - 2, 63)
    d.path("M858,86 L878,86 L878,150 L858,150", color=MUTED, sw=1.6)
    d.arrow(858, 150, 806, 150)

    for i, t in enumerate(bot):
        kind = "navy" if "IS-U" in t else "plain"
        d.box(24 + (4 - i) * 176, 172, 156, 46, [(t, 11.5, "bold")], kind)
        if i < len(bot) - 1:
            d.arrow(24 + (4 - i) * 176 - 2, 195, 24 + (3 - i) * 176 + 158, 195)
    d.path("M24,195 L10,195 L10,63 L22,63", color=MUTED, sw=1.6)

    d.box(24, 244, 856, 40,
          [("Every arrow is a system transaction. A meter that's in a van but shown as installed becomes a billing problem.",
            11.5, "bold")], "soft")
    emit(d, "device_lifecycle")


def build_all():
    map_of_voltville()
    isu_in_erp()
    six_pillars()
    architecture_layers()
    mass_activity()
    master_data_chain()
    frau_meyer_objects()
    mr_lifecycle()
    ami_chain()
    bakery_profile()
    rtp_interface()
    device_model()
    replacement_timeline()
    field_service_chain()
    device_lifecycle()


if __name__ == "__main__":
    build_all()
    for mod in ("make_diagrams_b", "make_diagrams_c"):
        __import__(mod).build_all()
    print(f"Wrote {len(BUILT)} diagrams to {os.path.abspath(OUT)}")
    for n in BUILT:
        print("  ", n + ".svg")
