#!/usr/bin/env python3
"""Generate the bestiary: one sheet per monster image, docs/monsters/bestiary/.

The values come from the monster blocks of the 16 LEVELn.INF files, read with
scripts/inf/inf_records.py (layout: formats/INF.ksy). What the files do not
give comes from scripts/monsters/bestiary.json: which image draws each type,
the description of each image, the number of placements by script, where the
monsters of a second sublevel record come from, and notes. The sheets and
their figures are generated: edit this program or the data file and run it
again, never the sheets.

The program writes:
  docs/monsters/bestiary/<IMAGE>.md     one sheet per image;
  docs/monsters/bestiary/img/*.svg      one comparison figure per sheet, the
                                        monsters by level and the capabilities;
  the table between the two generated-table markers of
  docs/monsters/bestiary/README.md.

Usage (from the repository root; --game DIR reads the game files from
another directory):
    python3 -I scripts/monsters/make_bestiary.py
"""
import argparse
import importlib.util
import json
import math
import re
import sys
from html import escape
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
OUT = ROOT / 'docs/monsters/bestiary'


def _load(name, *candidates):
    path = next(p for p in candidates if p.exists())
    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', ROOT / 'scripts/inf/script_decoder.py')
IR = _load('inf_records', HERE / 'inf_records.py', ROOT / 'scripts/inf/inf_records.py')

MINUS = '−'
FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
SURF, BORDER, INK, INK2, MUTED, GRID = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#8a8984', '#eeede9'
BLUE, LIGHT, DARK, SHADE = '#2a78d6', '#a9c9f0', '#1c5cab', '#f1f0ec'

# docs/enums/MONSTER_CAPABILITY_FLAGS.md, bits 0 to 15: name, what it means, rule page.
CAPABILITIES = [
    ('LARGE', 'Counts as large: weapons roll their second damage profile', '../../combat/DAMAGE.md#item-damage-profiles'),
    ('ALT_FRAME_TABLE', 'Drawn with the alternate frame table', '../../view/MONSTERS.md#monsters'),
    ('WALL_SPECIAL_TYPE_1', "The final opponent's own door and death rules", '../OBSTACLES.md#walls-and-doors'),
    ('POST_MOVE_ACTION', 'Tries a melee attack again after moving', '../README.md#choosing-an-action'),
    ('POISONS', 'Poisons with its melee attacks', '../MELEE_ATTACKS.md#effects-on-characters'),
    ('PARALYZES', 'Paralyzes with its melee attacks', '../MELEE_ATTACKS.md#effects-on-characters'),
    ('BIT_6_UNKNOWN', 'Bit 6, which no code tests', '../../enums/MONSTER_CAPABILITY_FLAGS.md#unused-bits'),
    ('ITEM_LOSS', 'Makes the character it hits lose an item three times in four', '../MELEE_ATTACKS.md#melee-attacks'),
    ('HIDDEN', 'Hidden', '../../enums/MONSTER_CAPABILITY_FLAGS.md'),
    ('SIDESTEP_SOMETIMES', 'Skips the sideways step one time in four', '../MOVING.md#moving-toward-the-destination'),
    ('BIT_10_UNKNOWN', 'Bit 10, which no code tests', '../../enums/MONSTER_CAPABILITY_FLAGS.md#unused-bits'),
    ('ATTACKS_ANY_SIDE', 'Attacks a party on any side without turning', '../MELEE_ATTACKS.md#what-stops-an-attack'),
    ('OPENS_DOORS', 'Opens closed doors that have a switch', '../OBSTACLES.md#walls-and-doors'),
    ('DIES_ON_HIT', 'Dies from any damage and explodes', '../DEATH.md#when-a-monster-dies'),
    ('ATTACKS_ALL', 'Attacks every character of its order', '../../party/FORMATION.md#who-a-monster-attacks'),
    ('PETRIFIES', 'Petrifies with its melee attacks', '../MELEE_ATTACKS.md#effects-on-characters'),
]
# docs/enums/MONSTER_IMMUNITY_FLAGS.md, bits 0 to 13.
IMMUNITIES = [
    ('BIT_0_UNKNOWN', 'Bit 0, which no code tests'),
    ('PARALYSIS', '*Hold Person*, *Hold Monster* and *Power Word Stun* have no effect'),
    ('FEAR', '*Fear* has no effect'),
    ('DEATH', '*Finger of Death* and *Slay Living* do not kill it'),
    ('MAGIC', 'Magic damage is cancelled and spell effects are evaded'),
    ('ELECTRICITY', 'Electrical damage is cancelled'),
    ('UNKNOWN_0040', 'Cancels a kind of damage that never occurs'),
    ('COLD', 'Cold damage is cancelled'),
    ('WEAPON_HALVED', 'Weapon damage is halved'),
    ('NEEDS_MAGIC_WEAPON', 'Only weapons of value above 0 hit it'),
    ('UNKNOWN_0400', 'Cancels a kind of damage that never occurs'),
    ('FIRE', 'Fire damage is cancelled'),
    ('NEEDS_PLUS_TWO', 'Only weapons of value above 1 hit it'),
    ('WEAPON_REDUCED', "Weapon damage is quartered or halved according to the weapon's value"),
]
HELD = [(1, '*Hold Person*'), (2, '*Hold Monster*'), (4, '*Turn undead*')]
# Magic flying objects 0 to 7 are the party's projectile spells (docs/magic/SPELLS.md#projectiles);
# only those that monsters launch are named here.
OBJECT_SPELLS = {0: 'Magic Missile', 2: 'Fireball', 3: 'Hold Person', 4: 'Lightning Bolt', 7: 'Flame Strike'}
THROWN_ITEMS = {4: 'Dagger'}   # ITEM.DAT entry 4
WORDS = {1: 'one', 2: 'two', 3: 'three', 4: 'four'}


# --------------------------------------------------------------------------- data

def load(game=None):
    if game:
        SD.ORIGINALS = game
    records = {}
    for level in range(1, 17):
        d = SD.load_levels([level])[0].data
        records[level] = IR.sublevels(d)
    data = json.loads((HERE / 'bestiary.json').read_text(encoding='utf-8'))
    monsters = data['monsters']
    seen = set()
    for m in monsters:
        for g in m['groups']:
            recs = records[g['level']]
            g['record_count'] = len(recs)
            rec = recs[g['record'] or 0]
            assert m['name'] in rec['banks'].values(), (m['name'], g)
            g['entries'] = [rec['type_entries'][t] for t in g['types']]
            for t in g['types']:
                key = (g['level'], g['record'] or 0, t)
                assert key not in seen, key
                seen.add(key)
            first = values(g['entries'][0])
            assert all(values(e) == first for e in g['entries']), (m['name'], g['types'])
    total = sum(len(r['type_entries']) for recs in records.values() for r in recs)
    assert len(seen) == total == 63, (len(seen), total)
    assert len(monsters) == 29
    assert sum(len(m['groups']) for m in monsters) == 57
    return monsters


def values(e):
    return (e['armor_class'], e['hit_chance'], e['level'], e['hit_points_dice'], e['attacks_per_round'],
            e['damage_dice'][:e['attacks_per_round']], e['experience'])


# --------------------------------------------------------------------------- formatting

def num(v):
    return f'{MINUS}{-v}' if v < 0 else str(v)


def dice(t):
    r, s, b = t
    if r == 0:
        return num(b)
    text = f'{r}d{s}'
    if b > 0:
        text += f' + {b}'
    elif b < 0:
        text += f' {MINUS} {-b}'
    return text


def dice_range(t):
    r, s, b = t
    return (r + b, r * s + b) if r else (b, b)


def join(items, word='and'):
    items = list(items)
    if len(items) <= 1:
        return ''.join(items)
    return ', '.join(items[:-1]) + f' {word} ' + items[-1]


def hit_points(e):
    return dice(e['hit_points_dice'])


def melee(e):
    return ', '.join(dice(t) for t in e['damage_dice'][:e['attacks_per_round']])


def melee_max(e):
    return sum(dice_range(t)[1] for t in e['damage_dice'][:e['attacks_per_round']])


def capability_names(e):
    return [CAPABILITIES[b][0] for b in range(16) if e['capability_flags'] >> b & 1]


def immunity_names(e):
    bits = [b for b in range(16) if e['immunity_flags'] >> b & 1]
    assert all(b < len(IMMUNITIES) for b in bits), bits
    return [IMMUNITIES[b][0] for b in bits]


def held_by(e):
    return [name for bit, name in HELD if e['type_flags'] & bit]


def weapon(w, plural=False):
    if w < 0:
        assert -w in THROWN_ITEMS, w
        return f'{THROWN_ITEMS[-w]} (item {-w})'
    if w in OBJECT_SPELLS:
        return f'*{OBJECT_SPELLS[w]}*'
    if 8 <= w <= 13:
        return f'monster spell {w}'
    assert w == 20, w
    return 'mind blast'


def ranged(e):
    n, weapons = e['remote_attack_count'], e['remote_weapons']
    if n == 0:
        return 'none'
    count = 'without limit' if n == 255 else WORDS.get(n, str(n)) if n == 1 else str(n)
    if all(8 <= w <= 13 for w in weapons) and len(weapons) > 1:
        names = 'monster spells ' + join(str(w) for w in weapons)
    else:
        names = ', '.join(weapon(w) for w in weapons)
    if len(weapons) == 1:
        return f'{count} {names}' if n == 1 else f'{count}: {names}'
    mode = {1: 'in turn', 2: 'at random'}[e['remote_weapon_change_mode']]
    return f'{count}, {mode}: {names}'


def decorations(e):
    groups = [str(d) for d in e['decoration_indices'] if d]
    return join(groups) if groups else 'none'


def sounds(e):
    return f"{num(e['sound_1'])}, {num(e['sound_2'])}"


def level_anchor(level):
    """The section of a level's pages that lists its monster types: its reference page first."""
    for name in (f'LEVEL_{level:02d}_REFERENCE.md', f'LEVEL_{level:02d}.md'):
        page = (ROOT / 'docs/world/levels' / name).read_text(encoding='utf-8')
        for title in ('Monster types', 'Monsters'):
            if re.search(rf'^#{{2,3}} {title}$', page, re.M):
                return f"{name}#{title.lower().replace(' ', '-')}"
    return f'LEVEL_{level:02d}.md'


def where(g):
    level = f"[{g['level']}](../../world/levels/{level_anchor(g['level'])})"
    return level + (f", record {g['record']}" if g['record_count'] > 1 else '')


def types_text(types):
    return ', '.join(str(t) for t in types)


def fix_links(text):
    """Links of bestiary.json are relative to docs/monsters/; the sheets sit one folder deeper."""
    return re.sub(r'\]\((?!https?:|#|/)([^)]+)\)', r'](../\1)', text)


def sheet_name(name):
    return name.upper()


# --------------------------------------------------------------------------- figures

def svg_frame(W, H, title, desc, subtitle):
    def text(x, y, s, size=12, fill=INK, bold=False, anchor='start'):
        b = ' font-weight="bold"' if bold else ''
        return (f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" fill="{fill}"{b} text-anchor="{anchor}" '
                f'dominant-baseline="central">{escape(s)}</text>')
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" '
           f'font-family="{FONT}">', f'<title>{escape(title)}</title>', f'<desc>{escape(desc)}</desc>',
           f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>',
           text(20, 26, title, 14, bold=True), text(20, 46, subtitle, 12, INK2)]
    return out, text


def write_svg(name, out):
    out.append('</svg>')
    (OUT / 'img').mkdir(parents=True, exist_ok=True)
    (OUT / 'img' / name).write_text('\n'.join(out) + '\n', encoding='utf-8')


MEASURES = [('Average hit points', lambda e: sum(dice_range(e['hit_points_dice'])) / 2),
            ('Melee damage per update, at most', melee_max),
            ('Experience for a kill', lambda e: e['experience'])]


def comparison(monster, everyone):
    name = monster['name']
    mine = [g['entries'][0] for g in monster['groups']]
    others = [g['entries'][0] for m in everyone for g in m['groups'] if m is not monster]
    W, H = 700, 270
    parts = []
    for label, f in MEASURES:
        vals = sorted({f(e) for e in mine})
        parts.append(f'{label.lower()}: ' + join(f'{v:,.0f}' for v in vals))
    desc = (f'The values of {name} compared with the 57 sets of values of the game, on logarithmic scales: '
            + '; '.join(parts) + '.')
    out, text = svg_frame(W, H, f'{name} among the monsters of the game', desc,
                          'Each dot is one set of values; logarithmic scales.')
    x0, x1 = 230, 670
    for i, (label, f) in enumerate(MEASURES):
        y = 92 + i * 56
        allv = [max(f(e), 1) for e in others + mine]
        lo, hi = math.log10(min(allv)), math.log10(max(allv))
        X = lambda v: x0 + (x1 - x0) * (math.log10(max(v, 1)) - lo) / (hi - lo)
        out.append(text(x0 - 14, y, label, 12, INK, False, 'end'))
        out.append(f'<line x1="{x0}" y1="{y}" x2="{x1}" y2="{y}" stroke="{GRID}" stroke-width="2"/>')
        for v in (min(allv), max(allv)):
            out.append(text(X(v), y + 18, f'{v:,.0f}', 10, INK2, False, 'middle'))
        for e in others:
            out.append(f'<circle cx="{X(f(e)):.1f}" cy="{y}" r="4" fill="{MUTED}" fill-opacity="0.35"/>')
        for e in mine:
            out.append(f'<circle cx="{X(f(e)):.1f}" cy="{y}" r="6.5" fill="{BLUE}" stroke="#ffffff" stroke-width="1.5"/>')
    out.append(f'<circle cx="236" cy="{H-22}" r="6" fill="{BLUE}"/>')
    out.append(text(248, H - 22, name, 11, INK2))
    out.append(f'<circle cx="{256 + 7 * len(name) + 20}" cy="{H-22}" r="4" fill="{MUTED}" fill-opacity="0.35"/>')
    out.append(text(256 + 7 * len(name) + 30, H - 22, 'every other set of values', 11, INK2))
    write_svg(f'{sheet_name(name)}.svg', out)
    return desc


def images_by_level(monsters):
    by_level = {}
    for m in monsters:
        for lv in sorted({g['level'] for g in m['groups']}):
            by_level.setdefault(lv, []).append(m['name'])
    W, rh = 700, 26
    H = 80 + 16 * rh + 20
    desc = 'The monster images that appear on each level, by name of image: ' + '; '.join(
        f'level {lv}: ' + (', '.join(by_level.get(lv, [])) or 'none') for lv in range(1, 17)) + '.'
    out, text = svg_frame(W, H, 'Which monsters live on each level', desc,
                          'By image name; two images appear on two levels, and level 10 has no monster.')
    for lv in range(1, 17):
        y = 80 + (lv - 1) * rh
        out.append(f'<rect x="20" y="{y}" width="{W-40}" height="{rh-4}" rx="4" fill="{SHADE if lv % 2 else SURF}"/>')
        out.append(text(32, y + (rh - 4) / 2, f'Level {lv}', 12, INK, True))
        x = 110
        for n in by_level.get(lv, []):
            w = 12 + 7.2 * len(n)
            out.append(f'<rect x="{x}" y="{y+3}" width="{w:.1f}" height="{rh-10}" rx="8" fill="{LIGHT}"/>')
            out.append(text(x + w / 2, y + (rh - 4) / 2, n, 11, DARK, False, 'middle'))
            x += w + 6
        if not by_level.get(lv):
            out.append(text(x, y + (rh - 4) / 2, 'no monster', 11, MUTED))
    write_svg('monster-images-by-level.svg', out)
    return desc


def capability_grid(monsters):
    caps = [b for b in range(16) if any(e['capability_flags'] >> b & 1
                                       for m in monsters for g in m['groups'] for e in g['entries'])]
    has = {(m['name'], b): any(e['capability_flags'] >> b & 1 for g in m['groups'] for e in g['entries'])
           for m in monsters for b in caps}
    W, cw, rh, left = 700, 16, 22, 210
    H = 124 + len(caps) * rh + 24
    desc = 'Which monster images have each capability in at least one of their types: ' + '; '.join(
        f'{CAPABILITIES[b][0]}: ' + ', '.join(m['name'] for m in monsters if has[(m['name'], b)]) for b in caps) + '.'
    out, text = svg_frame(W, H, 'Which monsters have which capability', desc,
                          'A dot when at least one type drawn with the image has the capability.')
    for j, m in enumerate(monsters):
        x = left + j * cw + 6
        out.append(f'<text x="{x:.1f}" y="112" font-size="10" fill="{INK2}" '
                   f'transform="rotate(-55 {x:.1f} 112)">{escape(m["name"])}</text>')
    for i, b in enumerate(caps):
        y = 124 + i * rh
        out.append(f'<rect x="20" y="{y}" width="{W-40}" height="{rh-2}" fill="{SHADE if i % 2 else SURF}"/>')
        out.append(text(28, y + rh / 2 - 1, CAPABILITIES[b][0], 11))
        for j, m in enumerate(monsters):
            if has[(m['name'], b)]:
                out.append(f'<circle cx="{left + j * cw + 6:.1f}" cy="{y + rh/2 - 1:.1f}" r="5" fill="{BLUE}"/>')
    write_svg('monster-capabilities.svg', out)
    return desc


# --------------------------------------------------------------------------- sheets

def rows_by(groups, key):
    """Rows of (level cell, types, entry) merging the types of one level whose key is equal."""
    rows = []
    for g in groups:
        for t, e in zip(g['types'], g['entries']):
            k = (where(g), key(e))
            if rows and rows[-1][0] == k:
                rows[-1][1].append(t)
            else:
                rows.append([k, [t], e])
    return [(k[0], types_text(ts), e) for k, ts, e in rows]


def table(header, rows, numeric=()):
    if header and header[0] == 'Level' and len({r[0] for r in rows}) == 1:
        header, rows = header[1:], [r[1:] for r in rows]
        numeric = tuple(i - 1 for i in numeric)
    align = ['---:' if i in numeric else '---' for i in range(len(header))]
    lines = ['| ' + ' | '.join(header) + ' |', '|' + '|'.join(align) + '|']
    lines += ['| ' + ' | '.join(r) + ' |' for r in rows]
    return '\n'.join(lines)


def placed(text):
    start, scripts = (int(x) for x in text.split('+'))
    parts = []
    if start:
        parts.append(f'{start} at the start')
    if scripts:
        parts.append(f"{scripts} placement instruction{'s' if scripts > 1 else ''} in the scripts")
    return join(parts) if parts else 'never placed by the level or its scripts'


def brief(m):
    name = m['name']
    desc = m['description']
    desc = desc[0].lower() + desc[1:]
    places = []
    for lv in sorted({g['level'] for g in m['groups']}):
        gs = [g for g in m['groups'] if g['level'] == lv]
        ts = sorted(t for g in gs for t in g['types'])
        rec = gs[0]['record'] if gs[0]['record_count'] > 1 else None
        where_ = f'level {lv}' + (f' (sublevel record {rec})' if rec is not None else '')
        inferred = [t for g in gs if '*inferred*' in g.get('note', '') for t in g['types']]
        mark = f" (type {join(str(t) for t in inferred)}: *inferred*)" if inferred else ''
        places.append(f"on {where_} by type{'s' if len(ts) > 1 else ''} {join(str(t) for t in ts)}{mark}")
    entries = [e for g in m['groups'] for e in g['entries']]
    hp = [dice_range(e['hit_points_dice']) for e in entries]
    lo, hi = min(h[0] for h in hp), max(h[1] for h in hp)
    xp = sorted({e['experience'] for e in entries})
    dmg = max(melee_max(e) for e in entries)
    attacks = sorted({e['attacks_per_round'] for e in entries})
    s = [f'The image of `{name}` shows {desc}' +
         (' The long form of its name, in parentheses, is a reading of the shortened name (*inferred*).'
          if '(' in desc else ''),
         f'It is used {join(places)}.' + (' No level or script places it directly: see where it comes from.'
                                        if all(g['placed'].replace(' ', '') == '0+0' for g in m['groups']) else ''),
         (f'It has {lo} to {hi} hit points' if lo != hi else f"It has {lo} hit point{'s' if lo != 1 else ''}") +
         f", makes {join((WORDS[a] for a in attacks), 'or')} hit roll{'s' if attacks[-1] > 1 else ''} in each melee "
         f'attack sequence, for {dmg} damage at most, and gives ' +
         (f'{xp[0]:,} experience' if len(xp) == 1 else f'{xp[0]:,} to {xp[-1]:,} experience') + ' for a kill.']
    abilities = []
    caps = set(b for e in entries for b in range(16) if e['capability_flags'] >> b & 1)
    for b in (4, 5, 15, 7, 14, 11, 12, 3, 13):
        if b in caps:
            abilities.append(CAPABILITIES[b][1][0].lower() + CAPABILITIES[b][1][1:])
    held = sorted({h for e in entries for h in held_by(e)}, key=[x[1] for x in HELD].index)
    if held:
        abilities.append('can be affected by ' + join(held))
    has = [w for w, ok in (('ranged attacks', any(e['remote_attack_count'] for e in entries)),
                           ('immunities', any(e['immunity_flags'] for e in entries))) if ok]
    if has:
        abilities.append('has ' + join(has))
    if abilities:
        s.append('It ' + join(abilities) + '.')
    return ' '.join(s)


def finding(m, everyone):
    """The caption of a sheet's figure: how its experience compares with the other sets of values."""
    best = max(e['experience'] for g in m['groups'] for e in g['entries'])
    others = [g['entries'][0]['experience'] for o in everyone if o is not m for g in o['groups']]
    below = sum(x < best for x in others)
    return (f"{m['name']} gives more experience than {below} of the {len(others)} other sets of values"
            + (', the most of all.' if below == len(others) else '.'))


def sheet(m, everyone):
    name = m['name']
    levels = sorted({g['level'] for g in m['groups']})
    nav = ' · '.join(['[Bestiary](README.md)'] +
                     [f'[Level {lv}](../../world/levels/{level_anchor(lv)})' for lv in levels] +
                     ['[How to read a sheet](README.md#reading-a-sheet)'])
    desc = comparison(m, everyone)
    out = [f'# {name}', '', nav, '',
           '## In brief', '', brief(m), '',
           f'![{desc}](img/{sheet_name(name)}.svg "{finding(m, everyone)}")', '']

    out += ['## Where it lives', '']
    for g in m['groups']:
        line = (f"- **Level {g['level']}" + (f", sublevel record {g['record']}" if g['record_count'] > 1 else '') +
                f"**, type{'s' if len(g['types']) > 1 else ''} {types_text(g['types'])}: {placed(g['placed'])}.")
        if g.get('note'):
            line += ' ' + fix_links(g['note'])
        out.append(line)
    for o in m['origin']:
        out += ['', f"**Where the monsters of level {o['level']}, record {o['record']}, come from.** " + fix_links(o['text'])]
    if any(re.search(r'\[\d\d:\d\d\]', o['text']) for o in m['origin']):
        out += ['', 'Positions are written `[XX:YY]`, column then row, both counted from `00`; the block index '
                'is `YY × 32 + XX`.']
    out.append('')

    out += ['## Values', '',
            table(['Level', 'Types', 'Armour class', 'Hit chance', 'Save level', 'Hit points', 'Melee damage',
                   'Experience'],
                  [[where(g), types_text(g['types']), num(e['armor_class']), num(e['hit_chance']), num(e['level']),
                    hit_points(e), melee(e), f"{e['experience']:,}"]
                   for g in m['groups'] for e in [g['entries'][0]]], numeric=(2, 3, 4, 7)), '']

    def abil(e):
        caps = capability_names(e)
        imm = immunity_names(e)
        return ('`' + '`, `'.join(caps) + '`' if caps else 'none', '`' + '`, `'.join(imm) + '`' if imm else 'none',
                join(held_by(e)) or 'none', ranged(e))
    rows = rows_by(m['groups'], abil)
    out += ['## Abilities', '',
            table(['Level', 'Types', 'Capabilities', 'Immunities', 'Held or turned by', 'Ranged attacks'],
                  [[w, t, *abil(e)] for w, t, e in rows]), '']
    entries = [e for g in m['groups'] for e in g['entries']]
    caps = sorted({b for e in entries for b in range(16) if e['capability_flags'] >> b & 1})
    imms = sorted({b for e in entries for b in range(16) if e['immunity_flags'] >> b & 1})
    if caps or imms:
        out.append('What they mean:')
        out.append('')
        for b in caps:
            n, text, link = CAPABILITIES[b]
            out.append(f'- `{n}`: [{text[0].lower() + text[1:]}]({link}).')
        for b in imms:
            n, text = IMMUNITIES[b]
            out.append(f'- `{n}`: [{text[0].lower() + text[1:]}](../../enums/MONSTER_IMMUNITY_FLAGS.md).')
        out.append('')
    if any(e['remote_attack_count'] for e in entries):
        out += ['How ranged attacks are chosen and timed: [ranged attacks](../RANGED_ATTACKS.md); the monster '
                'spells are described under [monster spells](../RANGED_ATTACKS.md#monster-spells).', '']

    def other(e):
        return (str(e['occupancy_class']), sounds(e), str(e['damage_modifier']), num(e['turn_resistance']),
                decorations(e))
    rows = rows_by(m['groups'], other)
    out += ['## Other values', '',
            table(['Level', 'Types', 'Occupancy class', 'Attack, step sound', 'Evasion', 'Turn resistance',
                   'Decoration groups'], [[w, t, *other(e)] for w, t, e in rows], numeric=(2, 4, 5)), '']

    out += ['## Sources', '',
            'This sheet is generated by [`make_bestiary.py`](../../../scripts/monsters/make_bestiary.py) from '
            'the monster blocks of ' + join(f'`LEVEL{lv}.INF`' for lv in levels) +
            ', read with the [INF schema](../../../formats/INF.ksy); the image of each type, the description and '
            'the placements by script come from its data file. See the [bestiary sources](README.md#sources).', '']
    (OUT / f'{sheet_name(name)}.md').write_text('\n'.join(out), encoding='utf-8')


# --------------------------------------------------------------------------- overview table

START, END = '<!-- generated table: start -->', '<!-- generated table: end -->'


def overview(monsters):
    rows = []
    for m in monsters:
        entries = [e for g in m['groups'] for e in g['entries']]
        hp = [dice_range(e['hit_points_dice']) for e in entries]
        xp = sorted({e['experience'] for e in entries})
        levels = sorted({g['level'] for g in m['groups']})
        lo, hi = min(h[0] for h in hp), max(h[1] for h in hp)
        rows.append([f"<a id=\"{m['name']}\"></a>[`{m['name']}`]({sheet_name(m['name'])}.md)",
                     ', '.join(f'[{lv}](../../world/levels/LEVEL_{lv:02d}.md)' for lv in levels),
                     str(sum(len(g['types']) for g in m['groups'])),
                     f'{lo}' if lo == hi else f'{lo}–{hi}',
                     str(max(melee_max(e) for e in entries)),
                     f'{xp[0]:,}' if len(xp) == 1 else f'{xp[0]:,}–{xp[-1]:,}'])
    text = table(['Monster', 'Levels', 'Types', 'Hit points', 'Melee damage, at most', 'Experience'], rows,
                 numeric=(2, 4))
    path = OUT / 'README.md'
    page = path.read_text(encoding='utf-8')
    a, b = page.index(START) + len(START), page.index(END)
    path.write_text(page[:a] + '\n\n' + text + '\n\n' + page[b:], encoding='utf-8')


def main():
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--game', type=Path, metavar='DIR', help='directory holding the game files')
    args = ap.parse_args()
    monsters = load(args.game)
    OUT.mkdir(parents=True, exist_ok=True)
    for m in monsters:
        sheet(m, monsters)
    images_by_level(monsters)
    capability_grid(monsters)
    if (OUT / 'README.md').exists():
        overview(monsters)
    print(f'{len(monsters)} sheets written to {OUT}')


if __name__ == '__main__':
    main()
