#!/usr/bin/env python3
"""Generate the figures of the items chapter, docs/items/.

The figures are original schematic drawings. The slot, defense, flight, pile
and location figures transcribe the rules of the chapter's pages; the two
decision chains use the shared module scripts/common/flowcharts.py. The two
catalogue charts read the table of docs/items/ITEM_TYPES.md, whose values come
from ITEMTYPE.DAT and ITEM.DAT. No game file and no game graphics are read.

Usage:
    python3 scripts/items/make_item_figures.py [output_directory]

The default is docs/items/img/.
"""
import re
import sys
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT / 'scripts/common')]
import flowcharts  # noqa: E402

PAGES = ROOT / 'docs/items'
OUT = Path(sys.argv[1]) if len(sys.argv) > 1 else PAGES / 'img'

FONT = flowcharts.FONT
SURF, BORDER, INK, INK2, MUTED, GRID = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#8a8984', '#eeede9'
BLUE, LIGHT, DARK, ORANGE, SHADE = '#2a78d6', '#a9c9f0', '#1c5cab', '#eb6834', '#f1f0ec'
text = flowcharts.text

# Values that the pages give and that the figures depend on.
DEX_16 = -2            # docs/party/ATTRIBUTES_AND_CLASSES.md, dexterity defense modifier
PLATE, SHIELD, BRACERS = -7, -1, 0   # ITEM_TYPES.md, Defense column of types 24, 27 and 43
MAX_HALF_BLOCKS = 13   # FLOOR_AND_THROWING.md


def frame(W, H, title, desc, subtitle):
    return [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" '
            f'role="img" 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, weight=True), text(20, 46, subtitle, 12, INK2),
            f'<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" '
            f'orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 Z" fill="{INK2}"/></marker></defs>']


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


def box(out, x, y, w, h, label, fill=SURF, stroke=BORDER, size=11.5, colour=INK, bold=False):
    out.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="6" fill="{fill}" stroke="{stroke}"/>')
    out += flowcharts.lines(x + w / 2, y + h / 2, label, size, 'middle', colour) if not bold else \
        [text(x + w / 2, y + h / 2, label, size, colour, True, 'middle')]


def arrow(out, x1, y1, x2, y2):
    out.append(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{INK2}" stroke-width="1.4" '
               f'marker-end="url(#ah)"/>')


# ------------------------------------------------------------- inventory slots
def inventory_slots():
    W, H = 700, 330
    desc = ('The 27 inventory slots of a character, grouped by use. Slots 0 and 1 are the two hands. Slots 2 to 15 '
            'are the backpack and accept any item. Slot 16 is the quiver, which holds a pile of arrows. Slots 17 '
            'to 21 hold body armour, bracers, a helmet, an amulet or necklace, and boots. Slot 22, the top belt '
            'slot, accepts any item; slots 23 and 24 accept small items. Slots 25 and 26 hold rings.')
    out = frame(W, H, 'The 27 inventory slots', desc,
                'Grouped by use; a slot takes an item whose type shares a bit of its mask.')
    c = 38

    def cells(x, y, first, n, per_row, fill, title):
        out.append(text(x, y - 12, title, 12, INK, True))
        for k in range(n):
            cx, cy = x + (k % per_row) * (c + 4), y + (k // per_row) * (c + 4)
            out.append(f'<rect x="{cx}" y="{cy}" width="{c}" height="{c}" rx="5" fill="{fill}" stroke="{BORDER}"/>')
            out.append(text(cx + c / 2, cy + c / 2, str(first + k), 12, INK, None, 'middle'))

    cells(20, 90, 0, 2, 2, LIGHT, 'Hands')
    cells(130, 90, 2, 14, 7, SHADE, 'Backpack: any item')
    cells(460, 90, 16, 1, 1, LIGHT, 'Quiver')
    out.append(text(460 + c + 8, 90 + c / 2, 'a pile of arrows', 11, INK2))
    worn = ['body armour', 'bracers', 'helmet', 'neck', 'boots']
    out.append(text(20, 198, 'Worn equipment', 12, INK, True))
    for k, label in enumerate(worn):
        x = 20 + k * 84
        out.append(f'<rect x="{x}" y="210" width="78" height="{c}" rx="5" fill="{LIGHT}" stroke="{BORDER}"/>')
        out.append(text(x + 39, 222, str(17 + k), 12, INK, None, 'middle'))
        out.append(text(x + 39, 238, label, 10, INK2, None, 'middle'))
    out.append(text(460, 198, 'Belt', 12, INK, True))
    out.append(f'<rect x="460" y="210" width="{c}" height="{c}" rx="5" fill="{SHADE}" stroke="{ORANGE}" stroke-width="1.5"/>')
    out.append(text(460 + c / 2, 210 + c / 2, '22', 12, INK, None, 'middle'))
    for k in range(2):
        x = 460 + (k + 1) * (c + 4)
        out.append(f'<rect x="{x}" y="210" width="{c}" height="{c}" rx="5" fill="{LIGHT}" stroke="{BORDER}"/>')
        out.append(text(x + c / 2, 210 + c / 2, str(23 + k), 12, INK, None, 'middle'))
    out.append(text(588, 198, 'Rings', 12, INK, True))
    for k in range(2):
        x = 588 + k * (c + 4)
        out.append(f'<rect x="{x}" y="210" width="{c}" height="{c}" rx="5" fill="{LIGHT}" stroke="{BORDER}"/>')
        out.append(text(x + c / 2, 210 + c / 2, str(25 + k), 12, INK, None, 'middle'))
    ly = 282
    for k, (fill, stroke, label) in enumerate([(SHADE, BORDER, 'any item'), (LIGHT, BORDER, 'items of matching types'),
                                               (SHADE, ORANGE, 'belt slot 22: any item, an anomaly')]):
        x = 20 + k * 200
        out.append(f'<rect x="{x}" y="{ly-9}" width="18" height="18" rx="3" fill="{fill}" stroke="{stroke}" stroke-width="1.5"/>')
        out.append(text(x + 26, ly, label, 11, INK2))
    write('items-inventory-slots.svg', out)


# ------------------------------------------------------------- defense
def defense():
    steps = [('Base', 10), ('Dexterity 16', DEX_16), ('+2 Plate Mail', PLATE - 2),
             ('+1 Shield in a hand', SHIELD - 1), ('+3 Bracers', BRACERS - 3)]
    total = sum(v for _, v in steps)
    assert total == -6, total
    W, H = 700, 360
    desc = ('A worked example of a character\'s defense, lower being better: base 10; dexterity 16 gives -2; '
            '+2 Plate Mail gives its type adjustment -7 less its value 2, so -9; a +1 Shield held in a hand gives '
            '-1 less 1, so -2; +3 Bracers of Protection give 0 less 3, so -3. The defense is -6. A Ring of '
            'Protection would add nothing, because the body armour is enchanted. The helmet, boots and amulet '
            'are never counted.')
    out = frame(W, H, 'How worn items set defense', desc,
                'A worked example: each item counts its type adjustment less its enchantment.')
    x0, x1, y0 = 220, 660, 80
    lo, hi = -8, 11
    X = lambda v: x0 + (x1 - x0) * (v - lo) / (hi - lo)
    for v in range(-8, 11, 2):
        out.append(f'<line x1="{X(v):.1f}" y1="{y0-6}" x2="{X(v):.1f}" y2="{y0 + len(steps) * 34 + 30}" stroke="{GRID}"/>')
        out.append(text(X(v), y0 + len(steps) * 34 + 42, str(v), 10, INK2, None, 'middle'))
    run = 0
    for i, (label, v) in enumerate(steps + [('Defense', None)]):
        y = y0 + i * 34
        out.append(text(x0 - 10, y + 11, label, 12, INK, i == len(steps), 'end'))
        if v is None:
            out.append(f'<rect x="{X(min(0, run)):.1f}" y="{y}" width="{abs(X(run) - X(0)):.1f}" height="22" rx="3" fill="{DARK}"/>')
            out.append(text(X(run) + 8, y + 11, str(run), 12, '#ffffff', True))
            continue
        a, b = run, run + v
        fill = SHADE if i == 0 else BLUE
        out.append(f'<rect x="{X(min(a, b)):.1f}" y="{y}" width="{abs(X(b) - X(a)):.1f}" height="22" rx="3" fill="{fill}"/>')
        out.append(text(X(max(a, b)) + 6, y + 11, f'{v:+d}' if i else str(v), 11, INK2))
        run = b
    out.append(text(20, H - 40, 'Not counted: the helmet, the boots and the amulet. A Ring of Protection counts only', 11, INK2))
    out.append(text(20, H - 24, 'when the body armour has value 0 or there is none.', 11, INK2))
    write('items-defense.svg', out)


# ------------------------------------------------------------- flight
def flight():
    W, H = 700, 250
    desc = ('A thrown item in flight. It starts in the party\'s block, in the front half for the first two '
            'characters and for mouse and keyboard throws, and advances half a block each time flying objects '
            f'move, for at most {MAX_HALF_BLOCKS} half-blocks. Each new block it enters receives a flying-object '
            'event. It stops at a face that does not let it through, after a hit, or at the end of its range, '
            'and falls in the quarter it has reached.')
    out = frame(W, H, 'A thrown item in flight', desc,
                f'Half a block at each move of the flying objects, {MAX_HALF_BLOCKS} half-blocks at most.')
    bw, x0, y0 = 80, 20, 92
    for k in range(8):
        x = x0 + k * bw
        out.append(f'<rect x="{x}" y="{y0}" width="{bw}" height="80" fill="{SHADE if k == 0 else SURF}" stroke="{BORDER}"/>')
        out.append(f'<line x1="{x + bw/2}" y1="{y0}" x2="{x + bw/2}" y2="{y0+80}" stroke="{GRID}" stroke-dasharray="3 3"/>')
        out.append(text(x + bw / 2, y0 + 96, "party's block" if k == 0 else f'+{k}', 10.5, INK2, None, 'middle'))
    start = x0 + bw * 0.75
    out.append(f'<circle cx="{start}" cy="{y0+40}" r="7" fill="{ORANGE}"/>')
    out.append(text(start, y0 - 12, 'start: front half', 10.5, INK2, None, 'middle'))
    for n in range(1, MAX_HALF_BLOCKS + 1):
        x = start + n * bw / 2
        out.append(f'<circle cx="{x}" cy="{y0+40}" r="4" fill="{BLUE}"/>')
        out.append(text(x, y0 + 58, str(n), 9.5, INK2, None, 'middle'))
    arrow(out, start + 10, y0 + 24, start + MAX_HALF_BLOCKS * bw / 2 - 6, y0 + 24)
    out.append(text(20, H - 40, 'Each new block entered receives a flying-object event. The flight ends at a face that', 11, INK2))
    out.append(text(20, H - 24, 'refuses the item, after a hit or at the end of its range; the item falls in that quarter.', 11, INK2))
    write('items-flight.svg', out)


# ------------------------------------------------------------- piles
def pile_order():
    dropped = [312, 45, 207]
    rebuilt = sorted(dropped)
    W, H = 700, 250
    desc = ('The order of a pile after the party leaves a level and comes back. Items dropped in the order entry '
            '312, entry 45, entry 207 lie with 207, the last dropped, on top. The level\'s piles are rebuilt in '
            'the order of the item table, so on return entry 312, the highest entry number, is on top, then 207, '
            'then 45.')
    out = frame(W, H, 'A pile rebuilt in table order', desc,
                'The order a player built by dropping items is lost when the level is loaded again.')

    def pile(x, title, items):
        out.append(text(x, 80, title, 12, INK, True))
        for k, n in enumerate(reversed(items)):
            y = 96 + k * 36
            out.append(f'<rect x="{x}" y="{y}" width="200" height="30" rx="5" fill="{LIGHT if k == 0 else SURF}" stroke="{BORDER}"/>')
            out.append(text(x + 12, y + 15, f'entry {n}', 12, INK))
            if k == 0:
                out.append(text(x + 188, y + 15, 'top', 11, DARK, True, 'end'))
    pile(30, 'Dropped: 312, then 45, then 207', dropped)
    arrow(out, 270, 150, 420, 150)
    out.append(text(345, 136, 'leave and come back', 11, INK2, None, 'middle'))
    pile(450, 'After the level is loaded again', rebuilt)
    write('items-pile-order.svg', out)


# ------------------------------------------------------------- where an item is
def life():
    W, H = 700, 340
    desc = ('Where an item entry can be. New items are copies of a template among the first hundred entries, made '
            'in the first unused entry. An item in play is on the floor or in a niche, in flight, carried in an '
            'inventory slot or on the pointer, or in a quiver. Its entry is freed, with block -1, when it is '
            'eaten, used up, spent, copied into the spellbook or removed by a script; an item taken by a monster '
            'leaves play without its entry being freed.')
    out = frame(W, H, 'Where an item entry can be', desc,
                'Templates are copied into free entries; an entry is freed when its item leaves the game.')
    box(out, 20, 132, 150, 56, 'Template\n(the first hundred entries)', SHADE, BORDER, 11)
    places = [('On the floor or in a niche', 'block, level; position 0–3 or 8'),
              ('In flight', 'block crossed; position 4–7'),
              ('Carried, or on the pointer', 'block 0, level 0'),
              ('In a quiver', 'block −2, level 255')]
    for k, (a, b) in enumerate(places):
        y = 76 + k * 46
        box(out, 250, y, 220, 38, f'{a}\n{b}', '#e9f1fb', BLUE, 11)
    arrow(out, 172, 160, 246, 160)
    out.append(text(209, 148, 'copy', 11, INK2, None, 'middle'))
    box(out, 550, 132, 130, 56, 'Free entry\nblock −1', SURF, INK2, 11.5)
    arrow(out, 472, 160, 546, 160)
    out.append(text(509, 130, 'eaten, used,', 10.5, INK2, None, 'middle'))
    out.append(text(509, 144, 'removed', 10.5, INK2, None, 'middle'))
    out.append(text(20, H - 56, 'A copy goes into the first unused entry from 1 upward; none is made when all 600 are in use.', 11, INK2))
    out.append(text(20, H - 40, 'An item taken by a monster leaves play without its entry being freed (an anomaly).', 11, INK2))
    out.append(text(20, H - 24, 'The whole table of 600 entries is saved with the game.', 11, INK2))
    write('items-life.svg', out)


# ------------------------------------------------------------- catalogue charts
def type_rows():
    lines = (PAGES / 'ITEM_TYPES.md').read_text(encoding='utf-8').splitlines()
    i = next(k for k, l in enumerate(lines) if l.startswith('| Type | Kind'))
    rows = []
    for l in lines[i + 2:]:
        if not l.startswith('|'):
            break
        rows.append([c.strip() for c in l.strip('|').split('|')])
    assert len(rows) == 64, len(rows)
    return rows


def records_by_kind():
    counts = {}
    for r in type_rows():
        kind = r[1].strip('`').replace('ITEM_KIND_', '').replace('_', ' ').lower()
        counts[kind] = counts.get(kind, 0) + int(r[8])
    counts = {k: v for k, v in counts.items() if v}
    total = sum(counts.values())
    assert total == 334, total
    items = sorted(counts.items(), key=lambda kv: -kv[1])
    W, rh = 700, 22
    H = 80 + len(items) * rh + 20
    desc = (f'The {total} items lying in the levels at the start of the game, by kind: ' +
            ', '.join(f'{k} {v}' for k, v in items) + '.')
    out = frame(W, H, 'What lies in the levels, by kind', desc,
                f'The {total} item records placed in the levels at the start of the game.')
    x0, x1 = 170, 640
    top = items[0][1]
    for k, (kind, v) in enumerate(items):
        y = 76 + k * rh
        out.append(text(x0 - 10, y + rh / 2 - 1, kind, 11.5, INK, None, 'end'))
        w = (x1 - x0) * v / top
        out.append(f'<rect x="{x0}" y="{y+3}" width="{w:.1f}" height="{rh-7}" rx="2" fill="{BLUE}"/>')
        out.append(text(x0 + w + 6, y + rh / 2 - 1, str(v), 11, INK2))
    write('items-records-by-kind.svg', out)


def dice(s):
    m = re.fullmatch(r'(\d+)d(\d+)(?:\+(\d+))?', s)
    n, d, b = int(m.group(1)), int(m.group(2)), int(m.group(3) or 0)
    return n + b, n * d + b


def weapon_damage():
    rows = []
    for r in type_rows():
        if r[5] == '—' or not r[9].strip() or r[9].startswith('No item') or r[9].startswith('Two records'):
            continue
        small, large = [dice(p.strip()) for p in r[5].split('/')]
        name = re.split(r'[,;→]', r[9])[0].replace('†', '').strip()
        rows.append((name, small, large))
    rows.sort(key=lambda t: -(t[2][1]))
    W, rh = 700, 26
    H = 96 + len(rows) * rh + 30
    desc = ('The damage dice of each weapon type, as a range from the lowest to the highest roll, against ordinary '
            'monsters and against large ones, before enchantment and strength: ' +
            '; '.join(f'{n} {a[0]}–{a[1]} and {b[0]}–{b[1]}' for n, a, b in rows) + '.')
    out = frame(W, H, 'Weapon damage, before enchantment', desc,
                'The range of each weapon type\'s dice, against ordinary monsters and against large ones.')
    x0, x1 = 190, 660
    top = max(t[2][1] for t in rows)
    X = lambda v: x0 + (x1 - x0) * v / top
    for v in range(0, top + 1, 2):
        out.append(f'<line x1="{X(v):.1f}" y1="78" x2="{X(v):.1f}" y2="{86 + len(rows) * rh}" stroke="{GRID}"/>')
        out.append(text(X(v), 92 + len(rows) * rh, str(v), 10, INK2, None, 'middle'))
    for k, (name, a, b) in enumerate(rows):
        y = 84 + k * rh
        out.append(text(x0 - 10, y + 9, name, 11.5, INK, None, 'end'))
        out.append(f'<rect x="{X(a[0]):.1f}" y="{y+1}" width="{max(X(a[1]) - X(a[0]), 3):.1f}" height="7" rx="2" fill="{BLUE}"/>')
        out.append(f'<rect x="{X(b[0]):.1f}" y="{y+10}" width="{max(X(b[1]) - X(b[0]), 3):.1f}" height="7" rx="2" fill="{ORANGE}"/>')
    ly = H - 18
    out.append(f'<rect x="190" y="{ly-5}" width="14" height="8" rx="2" fill="{BLUE}"/>')
    out.append(text(210, ly - 1, 'ordinary monsters', 11, INK2))
    out.append(f'<rect x="350" y="{ly-5}" width="14" height="8" rx="2" fill="{ORANGE}"/>')
    out.append(text(370, ly - 1, 'large monsters', 11, INK2))
    write('items-weapon-damage.svg', out)


# ------------------------------------------------------------- decision chains
def chains():
    flowcharts.chain(
        OUT / 'items-use.svg', 'Using the item in a hand',
        'What happens when a character uses a hand on its portrait.',
        'What happens when a character uses the item in one of its hands. Nothing happens unless the character '
        'is present, conscious and neither paralyzed nor petrified. A hand that is recovering waits; a hand '
        'that cannot be used, or whose item the class may not use, is refused without a message. Otherwise the '
        "item's kind decides what happens, and the block in front of the party receives the item-used event, "
        'except for a melee weapon used from the back rows.',
        [('ask', 'Is the character present, conscious,\nnot paralyzed or petrified?', 'no', 'Nothing happens', 'yes'),
         ('ask', 'Is the hand ready and usable,\nthe item allowed to the class?', 'no',
          'It waits, or is refused\nwithout a message', 'yes'),
         ('step', "The item's kind decides: an attack, a spell,\na potion, a text, food, a sound…"),
         ('step', 'The block in front of the party receives\nthe item-used event')],
        'A melee weapon used by a character in the back rows sends no event.')
    flowcharts.chain(
        OUT / 'items-item-cast.svg', 'Casting from an item',
        'Scrolls, the Fire Sphere, magic dust, wands and the Amulet of Life.',
        'How a spell is cast from an item. The item type\'s class mask decides who can cast from it. The spell '
        'is cast at caster level 9, without using a spell slot, and the item is spent at once: a scroll, sphere, '
        'dust or amulet is used up, a wand loses a charge. If the target is then cancelled or the spell refused, '
        'the item is not given back. Otherwise the spell takes effect; the hand recovers as after an attack and '
        'the spell book state is restored.',
        [('ask', "Does the item type's class mask\nallow the character?", 'no', 'Refused', 'yes'),
         ('step', 'Cast at caster level 9, with no spell slot;\nthe item is spent, or a wand loses a charge'),
         ('ask', 'Target chosen and spell accepted?', 'no', 'The item is not given back', 'yes'),
         ('step', 'The spell takes effect; the hand recovers\nas after an attack; the book is restored')])


if __name__ == '__main__':
    inventory_slots()
    defense()
    flight()
    pile_order()
    life()
    records_by_kind()
    weapon_damage()
    chains()
