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

The figures are original schematic drawings that follow the rules written on
the pages: the noticing zone is computed with the distance, direction and
sector formulas of docs/monsters/NOTICING.md; the move orders, modes, block
positions, ranged-attack waits and the pursuit, melee and death chains
transcribe README.md, MOVING.md, MODES.md, OBSTACLES.md, RANGED_ATTACKS.md,
MELEE_ATTACKS.md and DEATH.md. The bestiary and its figures are generated by
make_bestiary.py. No game file and no game graphics are read.

Usage:
    python3 scripts/monsters/make_monster_figures.py [output_directory]

The default is docs/monsters/img/.
"""
import math
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

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

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, ORANGE, SHADE, GREEN = '#2a78d6', '#a9c9f0', '#1c5cab', '#eb6834', '#f1f0ec', '#2f8f5b'


def text(x, y, s, size=12, fill=INK, weight=None, anchor='start'):
    w = ' font-weight="bold"' if weight else ''
    return (f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" fill="{fill}"{w} '
            f'text-anchor="{anchor}" dominant-baseline="central">{escape(s)}</text>')


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)]


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 arrow_up(cx, cy, size, colour):
    return (f'<path d="M{cx},{cy-size} L{cx+size*0.7},{cy+size*0.6} L{cx},{cy+size*0.25} '
            f'L{cx-size*0.7},{cy+size*0.6} Z" fill="{colour}"/>')


# ------------------------------------------------------------- noticing
def direction(dx, dy):
    """Direction from a block to another, 0 north to 7 north-west (NOTICING.md)."""
    if dx == 0 and dy == 0:
        return None
    if 2 * abs(dy) >= abs(dx) and 2 * abs(dx) >= abs(dy):
        if dx > 0:
            return 1 if dy < 0 else 3
        return 7 if dy < 0 else 5
    if abs(dy) > abs(dx):
        return 0 if dy < 0 else 4
    return 2 if dx > 0 else 6


def noticing():
    W, H = 700, 470
    R = 5
    cell = 34
    gx, gy = 40, 80
    desc = ('A monster facing north in the middle of a grid of blocks, and for each block around it whether a party '
            'standing there is noticed. Distance is the larger of the column and row differences plus half the '
            'smaller, rounded down; walls do not count. At distance 0 or 1 the party is always noticed. At '
            'distance 2 or 3 it is noticed unless it is in the sector behind the monster: south-west, south or '
            'south-east of it. At distance 4 or more it is not noticed.')
    out = frame(W, H, 'Where a monster notices the party', desc,
                'A monster facing north; walls are not taken into account.')
    for row in range(-R, R + 1):
        for col in range(-R, R + 1):
            x = gx + (col + R) * cell
            y = gy + (row + R) * cell
            dist = max(abs(col), abs(row)) + min(abs(col), abs(row)) // 2
            d = direction(col, row)
            if d is None:
                fill = DARK
            elif dist < 2:
                fill = DARK
            elif dist < 4:
                sector = d - 0 - 3
                if sector < 0:
                    sector += 8
                fill = BLUE if sector > 2 else SHADE
            else:
                fill = SURF
            out.append(f'<rect x="{x}" y="{y}" width="{cell-2}" height="{cell-2}" rx="3" fill="{fill}" stroke="{BORDER}"/>')
            if fill in (DARK, BLUE, SHADE) and d is not None:
                out.append(text(x + cell / 2 - 1, y + cell / 2 - 1, str(dist), 10,
                                '#ffffff' if fill in (DARK, BLUE) else INK2, anchor='middle'))
    mx = gx + R * cell + cell / 2 - 1
    my = gy + R * cell + cell / 2 - 1
    out.append(arrow_up(mx, my, 11, '#ffffff'))
    lx = gx + (2 * R + 1) * cell + 36
    items = [(DARK, 'Distance 0 or 1: always noticed'),
             (BLUE, 'Distance 2 or 3, not behind: noticed'),
             (SHADE, 'Distance 2 or 3, behind: not noticed'),
             (SURF, 'Distance 4 or more: not noticed')]
    for i, (fill, label) in enumerate(items):
        y = gy + 10 + i * 32
        out.append(f'<rect x="{lx}" y="{y-10}" width="20" height="20" rx="3" fill="{fill}" stroke="{BORDER}"/>')
        out.append(text(lx + 28, y, label, 12))
    out.append(text(lx, gy + 150, 'Numbers: distance in blocks.', 11, INK2))
    out.append(text(lx, gy + 168, 'The arrow: the monster, facing north.', 11, INK2))
    out.append(text(lx, gy + 186, 'Behind: south-west, south, south-east.', 11, INK2))
    write('monster-noticing.svg', out)


# ------------------------------------------------------------- move orders
def move_orders():
    W, H = 700, 300
    desc = ('The order in which a moving monster tries the directions around it, starting from the direction it '
            'turned to, here north. Diagonal directions are skipped. Order A tries north, then east, then west, '
            'then south; order B tries north, then west, then east, then south. The two orders alternate every '
            'eleven movement steps counted over all monsters together.')
    out = frame(W, H, 'The order in which a monster tries to move', desc,
                'From its starting direction s, here north; diagonals are skipped. The way back comes last.')
    names = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']

    def compass(cx, cy, title, seq):
        out.append(text(cx, cy - 108, title, 13, INK, True, 'middle'))
        out.append(f'<rect x="{cx-26}" y="{cy-26}" width="52" height="52" rx="6" fill="{SHADE}" stroke="{BORDER}"/>')
        out.append(arrow_up(cx, cy, 12, INK2))
        rank = {}
        k = 1
        for t in seq:
            if t % 2 == 0:
                rank[t] = k
                k += 1
        for dnum in range(8):
            a = math.radians(dnum * 45 - 90)
            x, y = cx + 72 * math.cos(a), cy + 72 * math.sin(a)
            if dnum in rank:
                out.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="17" fill="{BLUE}"/>')
                out.append(text(x, y, str(rank[dnum]), 14, '#ffffff', True, 'middle'))
            else:
                out.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="13" fill="{SURF}" stroke="{MUTED}" stroke-dasharray="3 3"/>')
            lx, ly = cx + 98 * math.cos(a), cy + 98 * math.sin(a)
            out.append(text(lx, ly, names[dnum], 10, INK2, anchor='middle'))

    s = 0
    order_a = [s, s + 1, s - 1, s + 2, s - 2, s + 3, s - 3, s + 4]
    order_b = [s, s - 1, s + 1, s - 2, s + 2, s - 3, s + 3, s + 4]
    compass(180, 170, 'Order A', [t % 8 for t in order_a])
    compass(500, 170, 'Order B', [t % 8 for t in order_b])
    write('monster-move-orders.svg', out)


# ------------------------------------------------------------- positions
def positions():
    W, H = 700, 330
    desc = ('A block holds four positions, 0 to 3, its quarters, numbered like the floor positions of items, and '
            'position 4, its centre. A monster of occupancy class 0 entering an occupied block takes the first free '
            'position in an order set by its facing, front half first: facing north 0, 1, 2, 3; east 1, 3, 0, 2; '
            'south 2, 3, 0, 1; west 0, 2, 1, 3. Class 1 monsters pair on the diagonal 0 and 3. Class 2 monsters '
            'never enter an occupied block.')
    out = frame(W, H, 'Where a monster stands in a block', desc,
                'Positions 0 to 3 are the quarters, 4 the centre; the order depends on the occupancy class.')
    # the block
    bx, by, s = 30, 90, 150
    out.append(f'<rect x="{bx}" y="{by}" width="{s}" height="{s}" rx="6" fill="{SURF}" stroke="{INK2}"/>')
    for i, (qx, qy) in enumerate([(0, 0), (1, 0), (0, 1), (1, 1)]):
        out.append(text(bx + s / 4 + qx * s / 2, by + s / 4 + qy * s / 2, str(i), 16, BLUE, True, 'middle'))
    out.append(f'<circle cx="{bx+s/2}" cy="{by+s/2}" r="14" fill="{LIGHT}"/>')
    out.append(text(bx + s / 2, by + s / 2, '4', 14, DARK, True, 'middle'))
    out.append(text(bx + s / 2, by - 12, 'north', 11, INK2, anchor='middle'))
    out.append(text(bx + s / 2, by + s + 18, 'The five positions', 12, INK, True, 'middle'))
    # class 0 orders
    orders = {'north': [0, 1, 2, 3], 'east': [1, 3, 0, 2], 'south': [2, 3, 0, 1], 'west': [0, 2, 1, 3]}
    ox = 220
    out.append(text(ox, by - 12, 'Class 0: first free position, by the entering monster\'s facing', 12, INK, True))
    ms = 64
    for k, (facing, order) in enumerate(orders.items()):
        x = ox + k * (ms + 50)
        y = by + 10
        out.append(f'<rect x="{x}" y="{y}" width="{ms}" height="{ms}" rx="4" fill="{SURF}" stroke="{BORDER}"/>')
        for rank, pos in enumerate(order):
            qx, qy = pos % 2, pos // 2
            out.append(text(x + ms / 4 + qx * ms / 2, y + ms / 4 + qy * ms / 2, str(rank + 1), 13,
                            BLUE if rank < 2 else INK2, rank < 2, 'middle'))
        out.append(text(x + ms / 2, y + ms + 14, f'facing {facing}', 11, INK2, anchor='middle'))
    # class 1 and 2
    y2 = by + 130
    x = ox
    out.append(text(x, y2, 'Class 1: pairs on the diagonal', 12, INK, True))
    out.append(f'<rect x="{x}" y="{y2+14}" width="{ms}" height="{ms}" rx="4" fill="{SURF}" stroke="{BORDER}"/>')
    out.append(f'<line x1="{x+ms/4+9}" y1="{y2+14+ms/4+9}" x2="{x+3*ms/4-9}" y2="{y2+14+3*ms/4-9}" stroke="{ORANGE}" stroke-width="2"/>')
    out.append(text(x + ms / 4, y2 + 14 + ms / 4, '0', 13, BLUE, True, 'middle'))
    out.append(text(x + 3 * ms / 4, y2 + 14 + 3 * ms / 4, '3', 13, BLUE, True, 'middle'))
    out.append(text(x + ms + 12, y2 + 30, 'with 0 taken it takes 3,', 11, INK2))
    out.append(text(x + ms + 12, y2 + 46, 'with 3 taken it takes 0', 11, INK2))
    x = ox + 2 * (ms + 50)
    out.append(text(x, y2, 'Class 2: alone', 12, INK, True))
    out.append(f'<rect x="{x}" y="{y2+14}" width="{ms}" height="{ms}" rx="4" fill="{SHADE}" stroke="{BORDER}"/>')
    out.append(text(x + ms + 12, y2 + 30, 'never enters an', 11, INK2))
    out.append(text(x + ms + 12, y2 + 46, 'occupied block', 11, INK2))
    out.append(text(ox, H - 22, 'A block with four monsters is full; all the monsters in a block share one class.', 11, INK2))
    write('monster-positions.svg', out)


# ------------------------------------------------------------- ranged waits
def ranged_waits():
    W, H = 700, 220
    steps = [('After an attack', 'counter 0', 'never fires', 0),
             ('Next update', 'counter 1', 'fires 1 time in 3', 1 / 3),
             ('Then', 'counter 2', 'fires 2 times in 3', 2 / 3),
             ('Then', 'counter 3', 'always fires', 1)]
    desc = ('The wait between two ranged attacks of a monster that keeps the party in line. After an attack the '
            'wait counter is 0 and the next try always waits; then the attack fires with one chance in three, '
            'then two in three, then always, because 1d3 must not be above the counter. Ranged attacks therefore '
            'come two to four updates apart.')
    out = frame(W, H, 'How long a monster waits between ranged attacks', desc,
                'At each pursuit update the monster rolls 1d3: above the wait counter, it waits and the counter rises.')
    bw, gap, x0, y0 = 150, 14, 24, 80
    for i, (title, counter, result, p) in enumerate(steps):
        x = x0 + i * (bw + gap)
        out.append(f'<rect x="{x}" y="{y0}" width="{bw}" height="96" rx="8" fill="{SURF}" stroke="{BORDER}"/>')
        out.append(text(x + 12, y0 + 18, title, 12, INK, True))
        out.append(text(x + 12, y0 + 36, counter, 11, INK2))
        out.append(f'<rect x="{x+12}" y="{y0+52}" width="{bw-24}" height="12" rx="3" fill="{SHADE}"/>')
        out.append(f'<rect x="{x+12}" y="{y0+52}" width="{(bw-24)*p:.1f}" height="12" rx="3" fill="{BLUE}"/>')
        out.append(text(x + 12, y0 + 80, result, 11.5, INK))
        if i < len(steps) - 1:
            ax = x + bw + 2
            out.append(f'<path d="M{ax},{y0+48} l10,6 l-10,6 Z" fill="{INK2}"/>')
    write('monster-ranged-waits.svg', out)


# ------------------------------------------------------------- modes
def modes():
    W, H = 700, 330
    desc = ('How a monster changes mode during play. A waiting, patrolling or wandering monster pursues the party '
            'when it notices it or is provoked; a pursuing monster starts wandering when the block ahead is its '
            'destination and the party is not there. A delayed or paralyzed monster pursues when its counter '
            'reaches zero. Every peaceful monster pursues when a peaceful monster is provoked by an attack or '
            'dies. Hold Person, Hold Monster and Power Word Stun paralyze a monster in any mode. Fear, Turn undead '
            'and a script that provokes a monster set the pursuit mode without changing the destination.')
    out = frame(W, H, 'How a monster changes mode', desc,
                'The modes a level or a script gives, and what moves a monster from one to another.')
    out.append(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 box(x, y, w, h, label, strong=False):
        out.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="8" fill="{BLUE if strong else "#e9f1fb"}" '
                   f'stroke="{BLUE}" stroke-width="1.5"/>')
        lines = label.split('\n')
        for i, l in enumerate(lines):
            out.append(text(x + w / 2, y + h / 2 + (i - (len(lines) - 1) / 2) * 15, l, 12.5,
                            '#ffffff' if strong else INK, strong, 'middle'))

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

    box(290, 186, 130, 48, 'Pursuing', True)
    box(20, 186, 170, 48, 'Waiting, patrolling,\nwandering')
    box(560, 186, 120, 48, 'Paralyzed')
    box(200, 80, 110, 40, 'Delayed')
    box(400, 80, 110, 40, 'Peaceful')
    arrow(190, 200, 288, 200)
    out.append(text(105, 172, 'notices the party, or provoked', 11, INK2))
    arrow(290, 222, 192, 222)
    out.append(text(105, 252, 'destination reached, party not there', 11, INK2))
    arrow(420, 200, 558, 200)
    out.append(text(490, 172, 'Hold spells, from any mode', 11, INK2, anchor='middle'))
    arrow(560, 222, 422, 222)
    out.append(text(490, 252, 'counter at zero', 11, INK2, anchor='middle'))
    arrow(270, 120, 320, 184)
    out.append(text(196, 146, 'counter at zero', 11, INK2))
    arrow(440, 120, 392, 184)
    out.append(text(520, 93, 'a peaceful monster', 11, INK2))
    out.append(text(520, 108, 'provoked or killed', 11, INK2))
    out.append(text(20, 290, 'Fear, Turn undead and a script that provokes a monster also set the pursuit mode;', 11, INK2))
    out.append(text(20, 306, 'only noticing the party, a provocation and the waking of peaceful monsters record its block.', 11, INK2))
    write('monster-modes.svg', out)


# ------------------------------------------------------------- decision chains
def chain(name, title, subtitle, desc, rows, note=None):
    flowcharts.chain(OUT / name, title, subtitle, desc, rows, note)


def pursuit():
    rows = [('ask', 'Is the block ahead the destination,\nwith the party not there?', 'yes', 'Start wandering, left or right\nat random', 'no'),
            ('ask', 'Ranged attack performed?', 'yes', 'End of the update', 'no'),
            ('ask', 'Melee attack performed?', 'yes', 'End of the update', 'no'),
            ('step', 'Move toward the destination'),
            ('ask', 'Type can act after moving?', 'yes', 'Try a melee attack again', None)]
    desc = ('The order of a pursuing monster\'s update. If the block ahead is its destination and the party is not '
            'there, it starts wandering, left or right at random. Otherwise it tries a ranged attack, then a melee '
            'attack; the update ends after either. If it did neither, it moves toward its destination, and a type '
            'that can act after moving then tries a melee attack again.')
    chain('monster-pursuit.svg', 'One pursuit update', 'A pursuing monster does one thing per update; '
          'moving comes last.', desc, rows)


def melee():
    rows = [('ask', 'Is the party in the block ahead?', 'no', 'Move toward the destination', 'yes'),
            ('ask', 'Standing on the half of its block\nfacing the party, or centre, or class 1?', 'no', 'Move within its block;\nthe update ends', 'yes'),
            ('ask', 'Does its alternating bit\nallow an attack this time?', 'no', 'No attack this update', 'yes'),
            ('step', 'One attack sequence against each\ncharacter it attacks'),
            ('step', 'If any attack hits: item loss, damage,\nthen poison, paralysis or petrification')]
    desc = ('When a pursuing monster attacks in melee. The party must be in the block ahead, otherwise the monster '
            'moves toward its destination. The monster must stand in the half of its block that faces the party, '
            'in its centre, or be of occupancy class 1, otherwise it moves within its block and its update ends. '
            'A bit of its state alternates at each chance, and only one value leads to an attack. It then runs one '
            'attack sequence against each character it attacks; when an attack hits, the character may lose an '
            'item, takes the damage, and may then be poisoned, paralyzed or petrified.')
    chain('monster-melee.svg', 'When a monster strikes in melee', 'Three conditions, then one attack sequence '
          'for each character attacked.', desc, rows)


def death():
    rows = [('ask', 'Does its type die on any hit?', 'yes', 'It explodes first: 6d6 to each\ncharacter if the party is near', 'then'),
            ('step', 'Its hit points become -1'),
            ('step', 'Its fixed item falls; its random item\none time in ten'),
            ('step', 'The party receives its experience,\nwhen the attack awards it'),
            ('step', 'It is placed on block [00:00]:\nexit and enter events'),
            ('ask', 'Was it peaceful?', 'yes', 'Every peaceful monster\npursues the party', None)]
    desc = ('What happens when a monster dies, in order. A type that dies on any hit explodes first, harming the '
            'party with 6d6 per character, halved by a saving throw, when the party is in its block or a '
            'neighbouring one. Then its hit points become -1; its fixed item falls, and its random item one time in '
            'ten; the party receives its experience when the attack awards it; it is placed on block [00:00], '
            'which sends exit and enter events; and if it was peaceful, every peaceful monster pursues the party. '
            'On level 16, sublevel 1, the final opponent skips the last two steps.')
    chain('monster-death.svg', 'When a monster dies', 'The steps in the order the game runs them.', desc, rows,
          'On level 16, sublevel 1, the final opponent skips the last two steps.')


if __name__ == '__main__':
    noticing()
    move_orders()
    positions()
    ranged_waits()
    modes()
    pursuit()
    melee()
    death()
