#!/usr/bin/env python3
"""Draw top-down maps of the EOB II DOS levels as SVG (research and documentation aid).

The maps are original schematic drawings computed from the game's own files:
the walls of LEVELn.MAZ, the wall mappings, doors, initial monsters and cell
bindings of LEVELn.INF (LCW-decoded in memory with tools/uncps.py) and the
items of ITEM.DAT. No game graphics or text are reproduced: scripts are
summarized by the kind of instruction they reach, not quoted.

Interpretation (see formats/MAZ.ksy, formats/INF.ksy and docs/enums/):
  * cell i is at column i mod 32, row i div 32; side s faces direction s
    (0 north, 1 east, 2 south, 3 west);
  * a side's wall reference is classified with the wall properties: the
    executable's built-in table for references 0-24, the sublevel's wall
    mappings (flags ^ 0x04) for the others, falling back to the first
    record's mappings for a later record; a reference still unmapped is drawn
    as a plain wall and reported on stderr (such faces are out of reach, see
    docs/world/WALLS_AND_DOORS.md#unmapped-wall-references);
  * a door block has its door faces on sides 0/2 when side 0 is a door,
    otherwise on sides 1/3;
  * script effects are the instructions reachable from the binding's entry
    point, following jumps, calls and both outcomes of each condition, except
    a comparison of two constants, which always takes the same outcome; so an
    effect may depend on conditions.

Usage (from the repository root; --game DIR reads the game files from another
directory, and the helper scripts script_decoder.py, inf_records.py and uncps.py may sit next
to this file instead of in the repository):
    python3 -I scripts/maps/make_level_maps.py                 # every level, sublevel 0
    python3 -I scripts/maps/make_level_maps.py 1 4             # some levels
    python3 -I scripts/maps/make_level_maps.py 1 --sublevel 1  # another sublevel record
    python3 -I scripts/maps/make_level_maps.py --all-sublevels --out DIR
    python3 -I scripts/maps/make_level_maps.py --key --out DIR      # the key of the symbols

The default output directory is build/level-maps/; the published maps are
generated with --out docs/world/img/level-maps. The originals are read only.
"""
import argparse
import importlib.util
import struct
import sys
from collections import OrderedDict, defaultdict
from html import escape
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]


def _load(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


SD = _load("script_decoder", HERE / "script_decoder.py" if (HERE / "script_decoder.py").exists()
            else ROOT / "scripts" / "inf" / "script_decoder.py")
P = SD.P
IR = _load("inf_records", HERE / "inf_records.py" if (HERE / "inf_records.py").exists()
            else ROOT / "scripts" / "inf" / "inf_records.py")
name13, parse_sublevel, sublevels, initial_monsters = IR.name13, IR.parse_sublevel, IR.sublevels, IR.initial_monsters

# Wall properties (docs/enums/WALL_RUNTIME_FLAGS.md).
PASSAGE, SMALL, MONSTER, DOOR, DOOR_OPEN, DOOR_CLOSED = 0x01, 0x02, 0x04, 0x08, 0x10, 0x20


def builtin_wall_flags():
    flags = [0] * 80
    flags[0] = PASSAGE | SMALL | MONSTER
    for base in (3, 8, 13, 18):
        flags[base] = DOOR | DOOR_CLOSED | 0x80
        for r in range(base + 1, base + 4):
            flags[r] = DOOR | 0x80
        flags[base + 4] = DOOR | DOOR_OPEN | 0x80 | PASSAGE | SMALL | MONSTER
    flags[23] = flags[24] = PASSAGE | SMALL
    return flags


SPECIAL_NAMES = {1: "door switch", 2: "wall button", 3: "lever", 4: "lever", 5: "door",
                 6: "door", 7: "scripted wall", 8: "wall button", 9: "scripted wall",
                 10: "niche"}
EVENT_NAMES = ["party enters", "party leaves", "item dropped", "item taken", "missile",
               "step count", "wall activated", "timer", "item used", "monster enters",
               "monster leaves", "spell cast"]


# docs/enums/SCRIPT_SEQUENCE_SELECTOR.md and docs/enums/SCRIPT_SPECIAL_EVENT.md.
SEQUENCES = {-2: "plays the portal animation", -1: "asks the copy-protection question",
             0: "Insal offers to join", 1: "Calandra's dialogue", 2: "Shorn's dialogue"}
SPECIAL_EVENTS = {0: "lightning", 1: "asks to choose a character", 2: "raises a character's level",
                  3: "resurrection", 4: "recruits a character", 5: "removes quest items",
                  6: "reloads the wall graphics"}


def item_data():
    d = SD.game_file("ITEM.DAT").read_bytes()
    n = struct.unpack_from("<H", d, 0)[0]
    items = [d[2 + 14 * i:16 + 14 * i] for i in range(n)]
    base = 2 + 14 * n
    names = [name13(d[base + 2 + 35 * i:base + 2 + 35 * (i + 1)])
             for i in range(struct.unpack_from("<H", d, base)[0])]
    return items, names


ITEMS, ITEM_NAMES = [], []          # read by main() once the game directory is known


def item_name(index):
    """The unidentified name, followed by the identified one when it differs."""
    rec = ITEMS[index]
    plain, known = (ITEM_NAMES[n] if n < len(ITEM_NAMES) else "" for n in rec[:2])
    if known and known != plain:
        return f"{plain} ({known})" if plain else known
    return plain or f"item {index}"


def level_items(level):
    out = defaultdict(list)
    for i, rec in enumerate(ITEMS):
        loc = struct.unpack_from("<H", rec, 6)[0]
        if rec[12] == level and 0 < loc < 0x8000:
            out[loc].append((rec[5], item_name(i)))
    return out


# --------------------------------------------------------------------------- scripts

CONSTANT_TESTS = {"==": lambda a, b: a == b, "!=": lambda a, b: a != b, "<": lambda a, b: a < b,
                  "<=": lambda a, b: a <= b, ">": lambda a, b: a > b, ">=": lambda a, b: a >= b}


def constant_outcome(insn):
    """True or False when a JUMP_UNLESS compares two constants, else None."""
    words = insn.text.split(";")[0].split()
    if len(words) == 3 and words[2] in CONSTANT_TESTS:
        try:
            return CONSTANT_TESTS[words[2]](int(words[0]), int(words[1]))
        except ValueError:
            return None
    return None


def reachable(level, entry):
    """Instructions reachable from one entry point, in address order.

    Both outcomes of a condition are followed, except when it compares two
    constants: then only the outcome it always takes."""
    buf, seen, work, out = level.buf, set(), [entry], {}
    while work:
        pos = work.pop()
        while 2 <= pos < level.message_offset and pos not in seen:
            seen.add(pos)
            if buf[pos] < 0xe2:
                pos += 1
                continue
            try:
                insn = SD.decode(buf, pos)
            except (SD.Truncated, SD.UnknownLayout):
                break
            out[pos] = insn
            outcome = constant_outcome(insn) if insn.flow == "cond" else None
            if insn.flow == "call" or (insn.flow == "cond" and outcome is not True):
                work.append(insn.target)
            if insn.flow == "cond" and outcome is False:
                break
            if insn.flow == "jump":
                pos = insn.target
            elif insn.flow in ("end", "return", "stop"):
                break
            else:
                pos += insn.length
    return [out[p] for p in sorted(out)]


def effects(insns, rec):
    """Short descriptions of what a script can do, and the party teleport targets."""
    found, teleports, conditional = OrderedDict(), [], False

    def add(text):
        found.setdefault(text, None)

    for insn in insns:
        k, t = insn.key, insn.text
        words = t.split()
        if k == "JUMP_UNLESS" and constant_outcome(insn) is None:
            conditional = True
        elif k == "LOAD_LEVEL_OR_MONSTERS" and words[0] == "LEVEL":
            sub = f", sublevel {words[3]}" if words[3] != "0" else ""
            add(f"goes to level {words[1]}{sub} at {words[4]}")
        elif k == "LOAD_LEVEL_OR_MONSTERS":
            add("loads monster graphics")
        elif k == "MOVE_PARTY_OR_OBJECT" and words[0] == "PARTY":
            add(f"teleports the party to {words[-1]}")
            teleports.append(words[-1])
        elif k == "MOVE_PARTY_OR_OBJECT" and words[0] == "MONSTERS":
            add(f"moves monsters {words[1]} → {words[3]}")
        elif k == "MOVE_PARTY_OR_OBJECT":
            add("moves items")
        elif k in ("OPEN_DOOR", "CLOSE_DOOR"):
            add(f"{'opens' if k == 'OPEN_DOOR' else 'closes'} door {words[0]}")
        elif k == "TOGGLE" and words[0] == "DOOR":
            add(f"opens or closes door {words[1]}")
        elif k in ("SET", "TOGGLE") and words[0].startswith("BLOCK"):
            add(f"changes walls at {words[1]}")
        elif k == "SET" and words[0] == "DIRECTION" or k == "CHANGE_DIRECTION":
            add("turns the party")
        elif k == "SPAWN_MONSTER":
            fields = dict(w.split("=") for w in words)
            bank = rec["banks"].get(0 if fields["graphics"] == "0" else 1, "?")
            add(f"places a monster ({bank}, type {fields['type']}) at {fields['block']}")
        elif k == "DAMAGE_CHARACTERS":
            fields = dict(w.split("=") for w in words)
            add(f"damages {'the party' if fields['character'] == 'ALL' else 'a character'}"
                f" ({fields['dice']})")
        elif k == "MODIFY_CHARACTER_HP":
            add("changes hit points")
        elif k == "LAUNCH_OBJECT":
            add(f"launches a missile from {words[3]}")
        elif k == "CREATE_ITEM":
            template = int(words[1])
            where = words[3]
            if template >= len(ITEMS):
                name = f"item {template}"
            elif not any(ITEMS[template]):
                name = f"an empty item (all-zero record {template})"
            else:
                name = item_name(template)
            add(f"creates {name}" + (f" at {where}" if where.startswith("[") else ""))
        elif k == "DELETE_ITEM":
            add("removes items")
        elif k == "MOVE_INVENTORY_ITEM_TO_BLOCK":
            add("drops a carried item")
        elif k == "PRINT_MESSAGE":
            add("message")
        elif k == "DIALOGUE" and words[0] in ("TEXT", "CHOICE"):
            add("dialogue" if words[0] == "TEXT" else "dialogue with a choice")
        elif k == "AWARD_EXPERIENCE":
            add(f"awards {words[-1]} experience")
        elif k == "IDENTIFY_ITEMS":
            add("identifies items")
        elif k == "RUN_SEQUENCE":
            add(SEQUENCES.get(int(words[-1]), f"runs sequence {words[-1]}"))
        elif k == "SPECIAL_EVENT":
            add(SPECIAL_EVENTS.get(int(words[-1]), f"special event {words[-1]}"))
    return list(found), teleports, conditional


# --------------------------------------------------------------------------- map model

class LevelMap:
    def __init__(self, number, sublevel):
        self.number = number
        self.level = SD.load_levels([number])[0]
        d = self.level.data
        records = sublevels(d)
        self.rec = records[min(sublevel, len(records) - 1)]
        self.sublevel = records.index(self.rec)
        self.sublevel_count = len(records)
        maze = records[0]["maze"]
        if "maze" in self.rec:
            maze = self.rec["maze"]
        self.maze_name = maze.upper()
        m = SD.game_file(self.maze_name).read_bytes()[6:6 + 4096]
        self.cells = [tuple(m[4 * i:4 * i + 4]) for i in range(1024)]
        # A later record is entered from the first one, so references it does not map
        # keep the first record's mappings (docs/world/README.md#unmapped-wall-references).
        self.mappings = dict(records[0]["mappings"])
        self.mappings.update(self.rec["mappings"])
        self.flags = builtin_wall_flags()
        for ref, mp in self.mappings.items():
            if ref < 80:
                self.flags[ref] = mp["flags"] ^ 0x04
        used = {ref for c in self.cells for ref in c}
        for ref in sorted(used):
            if ref >= 25 and ref not in self.mappings:
                print(f"LEVEL{number}: wall reference {ref} not mapped, drawn as a wall",
                      file=sys.stderr)
        self.monsters = initial_monsters(d)
        self.items = level_items(number)

    def side_kind(self, ref):
        f = self.flags[ref] if ref < 80 else 0
        if ref == 0:
            return "open"
        if f & DOOR:
            return "door"
        if f & PASSAGE:
            return "pass"
        return "wall"

    def special(self, ref):
        mp = self.mappings.get(ref)
        return mp["special"] if mp else 0

    def block_kind(self, i):
        kinds = [self.side_kind(r) for r in self.cells[i]]
        if "door" in kinds:
            return "door"
        if all(k == "wall" for k in kinds):
            return "solid"
        if all(k != "open" for k in kinds):
            return "pass"
        return "floor"

    def door_axis(self, i):
        """'ns' when the door faces are sides 0 and 2 (the party crosses north-south)."""
        return "ns" if self.side_kind(self.cells[i][0]) == "door" else "ew"

    def door_state(self, i):
        refs = [r for r in self.cells[i] if self.side_kind(r) == "door"]
        f = self.flags[refs[0]]
        return "open" if f & DOOR_OPEN else "closed" if f & DOOR_CLOSED else "ajar"


# --------------------------------------------------------------------------- drawing

FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
SURFACE, INK, INK2, MUTED, GRID = "#fcfcfb", "#0b0b0b", "#52514e", "#8a8984", "#dddcd7"
ROCK, FLOOR = "#4a4844", "#f4f2ec"
DOOR_INK, SWITCH_INK = "#8a4b14", "#2a78d6"
MONSTER_INK, ITEM_INK, SCRIPT_INK, LEVEL_INK = "#c8302c", "#2f8a3e", "#6a3fb5", "#d9822b"
CELL = 22
MARGIN_LEFT, MARGIN_TOP = 34, 74
WRAP = 84


def num(v):
    """A coordinate with at most two decimals."""
    return f"{round(v, 2):g}"


class Svg:
    """Collects elements; repeated presentation attributes become CSS classes."""

    def __init__(self):
        self.parts, self.classes = [], {}

    def add(self, s):
        self.parts.append(s)

    def cls(self, css):
        if css not in self.classes:
            self.classes[css] = f"k{len(self.classes)}"
        return self.classes[css]

    def style(self):
        rules = "".join(f".{name}{{{css}}}" for css, name in self.classes.items())
        return f"<style>{rules}</style>"

    def text(self, x, y, s, size=11, fill=INK, weight="normal", anchor="start"):
        k = self.cls(f"font-size:{size}px;fill:{fill};font-weight:{weight};"
                     f"text-anchor:{anchor};dominant-baseline:central")
        self.add(f'<text class="{k}" x="{num(x)}" y="{num(y)}">{escape(s)}</text>')

    def rect(self, x, y, w, h, fill="none", stroke="none", sw=1, extra=""):
        k = self.cls(f"fill:{fill};stroke:{stroke};stroke-width:{sw}")
        self.add(f'<rect class="{k}" x="{num(x)}" y="{num(y)}" width="{num(w)}" '
                 f'height="{num(h)}" {extra}/>'.replace(" />", "/>"))

    def line(self, x1, y1, x2, y2, stroke, sw=1, extra=""):
        k = self.cls(f"stroke:{stroke};stroke-width:{sw}")
        self.add(f'<line class="{k}" x1="{num(x1)}" y1="{num(y1)}" x2="{num(x2)}" '
                 f'y2="{num(y2)}" {extra}/>'.replace(" />", "/>"))

    def circle(self, x, y, r, fill, stroke="none", sw=1):
        k = self.cls(f"fill:{fill};stroke:{stroke};stroke-width:{sw}")
        self.add(f'<circle class="{k}" cx="{num(x)}" cy="{num(y)}" r="{num(r)}"/>')


def hatch(s, x, y, size, step=5):
    """Diagonal hatching of a square, drawn as clipped lines."""
    k = step
    while k < 2 * size:
        x1, y1 = (x + k, y) if k <= size else (x + size, y + k - size)
        x2, y2 = (x, y + k) if k <= size else (x + k - size, y + size)
        s.line(x1, y1, x2, y2, stroke=MUTED, sw=1.2)
        k += step


def wrap(text, width):
    lines, line = [], ""
    for word in text.split():
        if line and len(line) + 1 + len(word) > width:
            lines.append(line)
            line = word
        else:
            line = f"{line} {word}".strip()
    return lines + [line] if line else lines


def binding_events(lm, block, flags):
    events = [EVENT_NAMES[n] for n in range(12) if flags & (0x0008 << n)]
    if block == 0 and not flags:
        events.append("step count")
    if any(lm.special(r) in (2, 3, 4, 7, 8, 9) for r in lm.cells[block]):
        events.append("wall activated")
    for target, _ in lm.rec["timers"]:
        if target == block:
            events.append("timer")
    return list(OrderedDict.fromkeys(events)) or ["no enabled event"]


def draw(lm):
    open_blocks = [i for i in range(1024) if lm.block_kind(i) != "solid"]
    cols = [i % 32 for i in open_blocks]
    rows = [i // 32 for i in open_blocks]
    c0, c1 = max(min(cols) - 1, 0), min(max(cols) + 1, 31)
    r0, r1 = max(min(rows) - 1, 0), min(max(rows) + 1, 31)
    ox, oy = MARGIN_LEFT, MARGIN_TOP

    def xy(i):
        return ox + (i % 32 - c0) * CELL, oy + (i // 32 - r0) * CELL

    def inside(i):
        return c0 <= i % 32 <= c1 and r0 <= i // 32 <= r1

    map_w, map_h = (c1 - c0 + 1) * CELL, (r1 - r0 + 1) * CELL
    s = Svg()
    s.add(f'<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" '
          f'markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" '
          f'fill="{SCRIPT_INK}"/></marker></defs>')

    # Blocks: one rock background, then the open blocks.
    s.rect(ox, oy, map_w, map_h, fill=ROCK)
    for i in range(1024):
        if not inside(i):
            continue
        x, y = xy(i)
        kind = lm.block_kind(i)
        if kind == "solid":
            continue
        s.rect(x, y, CELL, CELL, fill=FLOOR, stroke=GRID, sw=0.5)
        if kind == "pass":
            hatch(s, x, y, CELL)
    # Odd walls on open blocks and wall specials facing open blocks.
    steps = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    for i in range(1024):
        if not inside(i):
            continue
        x, y = xy(i)
        kind = lm.block_kind(i)
        for side, ref in enumerate(lm.cells[i]):
            ends = [(x, y, x + CELL, y), (x + CELL, y, x + CELL, y + CELL),
                    (x, y + CELL, x + CELL, y + CELL), (x, y, x, y + CELL)][side]
            if kind in ("floor", "pass") and lm.side_kind(ref) == "wall":
                s.line(*ends, stroke=ROCK, sw=3, extra='stroke-linecap="square"')
            sp = lm.special(ref)
            if sp and kind in ("solid", "pass"):
                dx, dy = steps[side]
                n = (i % 32 + dx) + 32 * (i // 32 + dy)
                if 0 <= n < 1024 and lm.block_kind(n) != "solid":
                    mx, my = x + CELL / 2 + dx * CELL * 0.36, y + CELL / 2 + dy * CELL * 0.36
                    if sp == 10:
                        s.rect(mx - 3.5, my - 3.5, 7, 7, fill=FLOOR, stroke=SWITCH_INK, sw=1.5)
                    elif sp in (1, 5, 6):
                        pass
                    else:
                        s.circle(mx, my, 3.2, SWITCH_INK, stroke="#ffffff", sw=1)
    # Doors.
    for i in range(1024):
        if inside(i) and lm.block_kind(i) == "door":
            x, y = xy(i)
            state = lm.door_state(i)
            if lm.door_axis(i) == "ns":
                rx, ry, rw, rh = x + 2, y + CELL / 2 - 3, CELL - 4, 6
            else:
                rx, ry, rw, rh = x + CELL / 2 - 3, y + 2, 6, CELL - 4
            s.rect(rx, ry, rw, rh, fill=DOOR_INK if state == "closed" else FLOOR,
                   stroke=DOOR_INK, sw=1.5)
    # Items: small dots in the floor quarters, squares for niches.
    for block, entries in lm.items.items():
        if not inside(block):
            continue
        x, y = xy(block)
        for k, (pos, _) in enumerate(entries):
            if pos >= 8:
                s.rect(x + CELL / 2 - 2.5, y + CELL / 2 - 2.5, 5, 5, fill=ITEM_INK)
                continue
            qx, qy = (pos & 1), (pos >> 1) & 1
            s.circle(x + 5.5 + qx * 11 + (k % 2) * 1.5, y + 5.5 + qy * 11, 2.2, ITEM_INK)
    # Monsters.
    kinds = OrderedDict()
    for mon in lm.monsters:
        key = (lm.rec["banks"].get(mon["bank"], "?"), mon["type"])
        kinds.setdefault(key, chr(ord("A") + len(kinds)))
    for mon in lm.monsters:
        if not inside(mon["block"]):
            continue
        x, y = xy(mon["block"])
        pos = mon["position"]
        if pos >= 4:
            cx, cy = x + CELL / 2, y + CELL / 2
        else:
            cx, cy = x + 5.5 + (pos & 1) * 11, y + 5.5 + ((pos >> 1) & 1) * 11
        letter = kinds[(lm.rec["banks"].get(mon["bank"], "?"), mon["type"])]
        s.circle(cx, cy, 5, MONSTER_INK, stroke="#ffffff", sw=1)
        s.text(cx, cy + 0.5, letter, size=7, fill="#ffffff", weight="bold", anchor="middle")

    # Script bindings: one number per distinct script.
    numbers, entries = OrderedDict(), defaultdict(list)
    ordered = sorted(lm.level.bindings, key=lambda b: (b[0] // 32, b[0] % 32))
    for block, flags, ref in ordered:
        if ref:
            numbers.setdefault(ref, len(numbers) + 1)
            entries[ref].append((block, flags))
    legend, arrows = [], []
    for ref, number in numbers.items():
        insns = reachable(lm.level, ref)
        effs, teleports, conditional = effects(insns, lm.rec)
        level_change = any(e.startswith("goes to level") for e in effs)
        places = entries[ref]
        events = OrderedDict()
        for block, flags in places:
            for e in binding_events(lm, block, flags):
                events.setdefault(e, None)
            far = [t for t in dict.fromkeys(teleports)
                   if abs(int(t[1:3]) - block % 32) + abs(int(t[4:6]) - block // 32) > 1]
            if not any(e.startswith("goes to level") for e in effs) and len(far) == 1:
                for target in far:
                    arrows.append((block, target))
        legend.append((number, places, list(events), effs, conditional, level_change))
        for block, _ in places:
            if not inside(block):
                continue
            x, y = xy(block)
            color = LEVEL_INK if level_change else SCRIPT_INK
            label = str(number)
            w = 9 + 5 * (len(label) - 1)
            s.rect(x + CELL - w - 0.5, y + 0.5, w, 10, fill=color, extra='rx="2"')
            s.text(x + CELL - w / 2 - 0.5, y + 5.7, label, size=8, fill="#ffffff",
                   weight="bold", anchor="middle")
    for src, target in arrows:
        col, row = int(target[1:3]), int(target[4:6])
        dst = row * 32 + col
        if not (inside(src) and inside(dst)) or abs(src % 32 - col) + abs(src // 32 - row) <= 1:
            continue
        (x1, y1), (x2, y2) = xy(src), xy(dst)
        x1, y1, x2, y2 = x1 + CELL / 2, y1 + CELL / 2, x2 + CELL / 2, y2 + CELL / 2
        length = max(((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5, 1)
        bend = min(18, length * 0.2)
        mx = (x1 + x2) / 2 - (y2 - y1) / length * bend
        my = (y1 + y2) / 2 + (x2 - x1) / length * bend
        s.add(f'<path d="M{x1:g},{y1:g} Q{mx:g},{my:g} {x2:g},{y2:g}" fill="none" '
              f'stroke="{SCRIPT_INK}" stroke-width="1.3" stroke-dasharray="4 2" '
              f'marker-end="url(#arrow)" opacity="0.8"/>')

    # Coordinates.
    for c in range(c0, c1 + 1):
        s.text(ox + (c - c0) * CELL + CELL / 2, oy - 8, f"{c:02d}", size=8, fill=MUTED,
               anchor="middle")
    for r in range(r0, r1 + 1):
        s.text(ox - 5, oy + (r - r0) * CELL + CELL / 2, f"{r:02d}", size=8, fill=MUTED,
               anchor="end")
    s.text(ox - 5, oy - 8, "N↑", size=9, fill=INK2, weight="bold", anchor="end")

    # Key and numbered list, right of the map.
    lx = ox + map_w + 28
    ly = oy
    key = [("rock", "Wall"), ("hatch", "Passable wall face"), ("door", "Door (closed)"),
           ("dooropen", "Door (open)"), ("button", "Wall that reacts (button, lever, script)"),
           ("niche", "Niche"), ("monster", "Monster at the start"), ("item", "Item on the floor"),
           ("script", "Script binding"), ("level", "Script binding that changes level")]
    s.text(lx, ly, "Key", size=12, weight="bold")
    ly += 18
    for kind, label in key:
        if kind == "rock":
            s.rect(lx, ly - 6, 12, 12, fill=ROCK)
        elif kind == "hatch":
            s.rect(lx, ly - 6, 12, 12, fill=FLOOR, stroke=GRID, sw=0.5)
            hatch(s, lx, ly - 6, 12)
        elif kind in ("door", "dooropen"):
            s.rect(lx, ly - 3, 12, 6, fill=DOOR_INK if kind == "door" else FLOOR,
                   stroke=DOOR_INK, sw=1.5)
        elif kind == "button":
            s.circle(lx + 6, ly, 3.2, SWITCH_INK)
        elif kind == "niche":
            s.rect(lx + 2.5, ly - 3.5, 7, 7, fill=FLOOR, stroke=SWITCH_INK, sw=1.5)
        elif kind == "monster":
            s.circle(lx + 6, ly, 5, MONSTER_INK)
        elif kind == "item":
            s.circle(lx + 6, ly, 2.4, ITEM_INK)
        else:
            s.rect(lx, ly - 5, 12, 10, fill=SCRIPT_INK if kind == "script" else LEVEL_INK,
                   extra='rx="2"')
        s.text(lx + 20, ly, label, size=10.5, fill=INK2)
        ly += 16
    ly += 8
    if kinds:
        s.text(lx, ly, "Monsters", size=12, weight="bold")
        ly += 18
        counts = defaultdict(int)
        for mon in lm.monsters:
            counts[(lm.rec["banks"].get(mon["bank"], "?"), mon["type"])] += 1
        for (bank, typ), letter in kinds.items():
            s.circle(lx + 6, ly, 5, MONSTER_INK)
            s.text(lx + 6, ly + 0.5, letter, size=7, fill="#ffffff", weight="bold",
                   anchor="middle")
            s.text(lx + 20, ly, f"{bank}, type {typ} × {counts[(bank, typ)]}", size=10.5,
                   fill=INK2)
            ly += 16
        ly += 8

    # Scripts and items below the map, in two balanced columns.
    blocks = []                                   # (badge or None, [(text, bold)])
    for number, places, events, effs, conditional, level_change in legend:
        where = ", ".join(P(b) for b, _ in places)
        lines = [(t, True) for t in wrap(where + " — on " + ", ".join(events), WRAP)]
        what = "; ".join(effs) if effs else "no visible effect"
        if conditional:
            what += " (conditions apply)"
        lines += [(t, False) for t in wrap(what, WRAP)]
        blocks.append(((number, level_change), lines))
    item_blocks = []
    for block in sorted(lm.items, key=lambda b: (b // 32, b % 32)):
        names = [n for _, n in lm.items[block]]
        item_blocks.append((None, [(t, False) for t in wrap(f"{P(block)}  " + ", ".join(names),
                                                             WRAP + 6)]))
    top = max(oy + map_h + 34, ly + 10)
    col_w = max((lx + 330 - ox) / 2, 470)
    width = int(ox + 2 * col_w + 10)

    def flow(title, entries, y0):
        """Lay out entries in two columns of about equal height; returns the bottom."""
        s.text(ox, y0, title, size=12, weight="bold")
        y0 += 20
        heights = [13 * len(lines) + 4 for _, lines in entries]
        half, acc, split = sum(heights) / 2, 0, len(entries)
        for k, h in enumerate(heights):
            if acc + h / 2 > half:
                split = k
                break
            acc += h
        bottom = y0
        for col, part in enumerate((entries[:split], entries[split:])):
            x, y = ox + col * col_w, y0
            for badge, lines in part:
                indent = 0
                if badge:
                    number, level_change = badge
                    w = 9 + 5 * (len(str(number)) - 1)
                    s.rect(x, y - 5, w, 10, fill=LEVEL_INK if level_change else SCRIPT_INK,
                           extra='rx="2"')
                    s.text(x + w / 2, y + 0.2, str(number), size=8, fill="#ffffff",
                           weight="bold", anchor="middle")
                    indent = 18
                for k, (line, bold) in enumerate(lines):
                    s.text(x + indent + (0 if badge or k == 0 else 12), y, line, size=10,
                           fill=INK if bold else INK2, weight="bold" if bold else "normal")
                    y += 13
                y += 4
            bottom = max(bottom, y)
        return bottom

    ly = flow("Scripts", blocks, top) + 12
    if item_blocks:
        ly = flow("Items on the floor and in niches", item_blocks, ly) + 12

    height = int(max(oy + map_h + 30, ly + 10))
    title = (f"Level {lm.number}" + (f", sublevel {lm.sublevel}" if lm.sublevel_count > 1 else "")
             + f" — {lm.maze_name}, {lm.rec.get('graphics', '')} graphics")
    # Shown at most 700 pixels wide in the pages, like every figure; the drawing scales.
    shown_w = min(width, 700)
    shown_h = round(height * shown_w / width)
    head = (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
            f'width="{shown_w}" height="{shown_h}" role="img" font-family="{FONT}">'
            f'<title>{escape(title)}</title>'
            f'<desc>Top-down map of level {lm.number} computed from {lm.maze_name}, '
            f'LEVEL{lm.number}.INF and ITEM.DAT, with walls, doors, reacting walls, initial '
            f'monsters, floor items and numbered script bindings.</desc>'
            f'<rect x="0.5" y="0.5" width="{width - 1}" height="{height - 1}" rx="10" '
            f'fill="{SURFACE}" stroke="{GRID}"/>'
            f'<text x="{MARGIN_LEFT}" y="30" font-size="16" font-weight="bold" fill="{INK}" '
            f'dominant-baseline="central">{escape(title)}</text>'
            f'<text x="{MARGIN_LEFT}" y="50" font-size="10.5" fill="{INK2}" '
            f'dominant-baseline="central">Positions are [column:row]; row 00 is the northern '
            f'edge. Each script lists what it can do; some effects depend on conditions.</text>')
    return head + s.style() + "\n".join(s.parts) + "</svg>\n"


def draw_key():
    """The symbols of the maps, each drawn on made-up blocks, for the page that explains them."""
    s = Svg()
    s.add('<defs><marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" '
          'markerHeight="6" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" '
          f'fill="{SCRIPT_INK}"/></marker></defs>')
    C = CELL

    def floor(x, y):
        s.rect(x, y, C, C, fill=FLOOR, stroke=GRID, sw=0.5)

    def badge(x, y, label, color):
        w = 9 + 5 * (len(label) - 1)
        s.rect(x + C - w - 0.5, y + 0.5, w, 10, fill=color, extra='rx="2"')
        s.text(x + C - w / 2 - 0.5, y + 5.7, label, size=8, fill="#ffffff", weight="bold",
               anchor="middle")

    def sample(kind, x, y):
        if kind == "rock":
            s.rect(x, y, C, C, fill=ROCK)
        elif kind == "edge":
            floor(x, y)
            s.line(x + C, y, x + C, y + C, stroke=ROCK, sw=3, extra='stroke-linecap="square"')
        elif kind == "hatch":
            floor(x, y)
            hatch(s, x, y, C)
        elif kind == "doors":
            for k, closed in enumerate((True, False)):
                floor(x + k * (C + 6), y)
                s.rect(x + k * (C + 6) + 2, y + C / 2 - 3, C - 4, 6,
                       fill=DOOR_INK if closed else FLOOR, stroke=DOOR_INK, sw=1.5)
        elif kind == "button":
            s.rect(x, y, C, C, fill=ROCK)
            floor(x + C, y)
            s.circle(x + C + C / 2 - C * 0.36, y + C / 2, 3.2, SWITCH_INK, stroke="#ffffff", sw=1)
        elif kind == "niche":
            s.rect(x, y, C, C, fill=ROCK)
            floor(x + C, y)
            mx = x + C + C / 2 - C * 0.36
            s.rect(mx - 3.5, y + C / 2 - 3.5, 7, 7, fill=FLOOR, stroke=SWITCH_INK, sw=1.5)
        elif kind == "monster":
            floor(x, y)
            s.circle(x + 5.5, y + 16.5, 5, MONSTER_INK, stroke="#ffffff", sw=1)
            s.text(x + 5.5, y + 17, "A", size=7, fill="#ffffff", weight="bold", anchor="middle")
        elif kind == "items":
            floor(x, y)
            s.circle(x + 5.5, y + 5.5, 2.2, ITEM_INK)
            s.circle(x + 16.5, y + 16.5, 2.2, ITEM_INK)
            floor(x + C + 6, y)
            s.rect(x + C + 6 + C / 2 - 2.5, y + C / 2 - 2.5, 5, 5, fill=ITEM_INK)
        elif kind == "script":
            floor(x, y)
            badge(x, y, "7", SCRIPT_INK)
        elif kind == "level":
            floor(x, y)
            badge(x, y, "3", LEVEL_INK)
        elif kind == "arrow":
            floor(x, y)
            floor(x + 2 * C, y)
            badge(x, y, "5", SCRIPT_INK)
            s.add(f'<path d="M{num(x + C / 2)},{num(y + C / 2)} Q{num(x + 1.5 * C)},'
                  f'{num(y + C + 4)} {num(x + 2.5 * C)},{num(y + C / 2)}" fill="none" '
                  f'stroke="{SCRIPT_INK}" stroke-width="1.3" stroke-dasharray="4 2" '
                  f'marker-end="url(#arrow)" opacity="0.8"/>')

    rows = [("rock", "Block that stops the party on all sides"),
            ("edge", "Open block; thick edge: a face that stops it"),
            ("hatch", "Walls on all faces, one at least passable"),
            ("doors", "Door, closed and open at the start"),
            ("button", "Wall face that reacts when used"),
            ("niche", "Niche"),
            ("monster", "Monster placed at the start, with its letter"),
            ("items", "Items on the floor; an item in a niche"),
            ("script", "Block with a script, numbered"),
            ("level", "Script that can change level"),
            ("arrow", "Where a script sends the party")]
    x0, y0, row_h, col_w, zoom = 24, 74, 46, 410, 1.6
    half = (len(rows) + 1) // 2
    for k, (kind, label) in enumerate(rows):
        col, row = divmod(k, half)
        x, y = x0 + col * col_w, y0 + row * row_h
        s.add(f'<g transform="translate({x} {y}) scale({zoom})">')
        sample(kind, 0, 0)
        s.add('</g>')
        s.text(x + 118, y + zoom * C / 2, label, size=13, fill=INK2)
    width = x0 + 2 * col_w
    height = y0 + half * row_h + 10
    head = (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
            f'width="700" height="{round(height * 700 / width)}" role="img" font-family="{FONT}">'
            '<title>The symbols of the level maps</title>'
            '<desc>Each symbol of the level maps drawn on made-up blocks, with its meaning.</desc>'
            f'<rect x="0.5" y="0.5" width="{width - 1}" height="{height - 1}" rx="10" '
            f'fill="{SURFACE}" stroke="{GRID}"/>'
            f'<text x="{x0}" y="26" font-size="16" font-weight="bold" fill="{INK}" '
            'dominant-baseline="central">The symbols of the level maps</text>'
            f'<text x="{x0}" y="48" font-size="13" fill="{INK2}" dominant-baseline="central">'
            'Made-up blocks, drawn as on the maps; north is up.</text>')
    return head + s.style() + "\n".join(s.parts) + "</svg>\n"


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("levels", nargs="*", type=int, default=list(range(1, 17)))
    ap.add_argument("--sublevel", type=int, default=0)
    ap.add_argument("--all-sublevels", action="store_true",
                    help="draw every sublevel record of each level")
    ap.add_argument("--out", type=Path, default=ROOT / "build" / "level-maps")
    ap.add_argument("--key", action="store_true",
                    help="draw only the key of the symbols, level-maps-key.svg")
    ap.add_argument("--game", type=Path, metavar="DIR",
                    help="directory holding the game files (default: data/originals/eob2)")
    args = ap.parse_args()
    if args.key:
        args.out.mkdir(parents=True, exist_ok=True)
        path = (args.out / "level-maps-key.svg").resolve()
        path.write_text(draw_key(), encoding="utf-8")
        print(path.relative_to(ROOT) if path.is_relative_to(ROOT) else path)
        return
    if args.game:
        SD.ORIGINALS = args.game
    ITEMS[:], ITEM_NAMES[:] = item_data()
    args.out.mkdir(parents=True, exist_ok=True)
    for n in args.levels:
        lm = LevelMap(n, args.sublevel)
        subs = range(lm.sublevel_count) if args.all_sublevels else [lm.sublevel]
        for sub in subs:
            if sub != lm.sublevel:
                lm = LevelMap(n, sub)
            suffix = f"-sub{lm.sublevel}" if lm.sublevel_count > 1 else ""
            path = (args.out / f"level-{n:02d}{suffix}-map.svg").resolve()
            path.write_text(draw(lm), encoding="utf-8")
            print(path.relative_to(ROOT) if path.is_relative_to(ROOT) else path)


if __name__ == "__main__":
    main()
