#!/usr/bin/env python3
"""Generate the figures of the scripts chapter and of the script virtual machine.

The figures are original schematic drawings that transcribe the rules written
on the pages of docs/scripts/ and docs/scripting/; the decoding chart uses the
counts of docs/scripting/DECODING.md, which come from the reachability decoder
of scripts/inf/script_decoder.py. The program reads no file.

Usage:
    python3 scripts/scripting/make_script_figures.py [scripts_dir] [scripting_dir]

The defaults are docs/scripts/img/ and docs/scripting/img/.
"""
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/scripts/img'
VM = Path(sys.argv[2]) if len(sys.argv) > 2 else ROOT / 'docs/scripting/img'

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

# docs/scripting/DECODING.md
SCRIPT_BYTES, REACHED = 65583, 65328
UNREACHED = [('dead code after level changes', 232), ('repeated returns', 5), ('two unreferenced routines', 18)]


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(folder, name, parts):
    parts.append('</svg>')
    folder.mkdir(parents=True, exist_ok=True)
    (folder / name).write_text('\n'.join(parts) + '\n', encoding='utf-8')
    print(folder / name)


def box(out, x, y, w, h, label, kind='step', size=11.5):
    fill, stroke = {'step': (SURF, INK2), 'state': (PALE, BLUE), 'strong': (BLUE, BLUE), 'end': (SHADE, BORDER)}[kind]
    out.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="8" fill="{fill}" stroke="{stroke}" stroke-width="1.4"/>')
    out.extend(flowcharts.lines(x + w / 2, y + h / 2, label, size, 'middle', '#ffffff' if kind == 'strong' else INK))


def arrow(out, d, label=None, lx=0, ly=0, anchor='middle', dash=False):
    extra = ' stroke-dasharray="4 3"' if dash else ''
    out.append(f'<path d="{d}" fill="none" stroke="{INK2}" stroke-width="1.4"{extra} marker-end="url(#ah)"/>')
    if label:
        out.append(text(lx, ly, label, 10.5, INK2, None, anchor))


# ------------------------------------------------------------- scripts chapter
def overview():
    W, H = 700, 330
    events = ['party enters or leaves', 'item put down or taken', 'item used', 'flying object arrives',
              'wall clicked', 'timer expires', 'step count reached', 'monster enters or leaves', 'spell cast']
    changes = ['walls and doors', 'the party, monsters, items', 'characters and flags',
               'messages, dialogues, sounds', 'another level']
    desc = ('How level scripts work. An event reaches a block: ' + ', '.join(events) + '. If the block has a script '
            'and accepts the event, a run starts at that script. The run tests conditions and executes commands '
            'until it stops; the commands change ' + ', '.join(changes) + '. The run ends before the game goes on.')
    out = frame(W, H, 'From an event to a change in the world', desc,
                'A run starts only when the block has a script and accepts the event; it ends before the game goes on.')
    out.append(text(20, 78, 'Events', 12, INK, True))
    for i, e in enumerate(events):
        y = 90 + i * 24
        out.append(f'<rect x="20" y="{y}" width="170" height="20" rx="4" fill="{SHADE}"/>')
        out.append(text(28, y + 10, e, 10.5, INK))
    box(out, 225, 150, 115, 70, "The block's\nscript, if the\nblock accepts\nthe event", 'state', 11)
    box(out, 375, 150, 115, 70, 'A run:\nconditions and\ncommands', 'strong', 11.5)
    arrow(out, 'M190,185 L222,185')
    arrow(out, 'M340,185 L372,185')
    out.append(text(520, 78, 'Changes', 12, INK, True))
    for i, c in enumerate(changes):
        y = 100 + i * 34
        out.append(f'<rect x="520" y="{y}" width="160" height="26" rx="4" fill="{PALE}" stroke="{BLUE}"/>')
        out.append(text(530, y + 13, c, 10.5, INK))
        arrow(out, f'M490,185 L517,{y + 13}')
    write(OUT, 'scripts-overview.svg', out)


def block_event():
    flowcharts.chain(
        OUT / 'scripts-block-event.svg', 'When an event reaches a block',
        'A block runs its script only for the events it accepts.',
        "What happens when an event reaches a block. If the block has no script, nothing runs. If it has one but "
        "does not accept the event, nothing runs either. Otherwise a run starts at the block's script and "
        'executes until it stops, and control returns to the caller.',
        [('step', 'An event in a block'),
         ('ask', 'Has the block a script?', 'no', 'Nothing runs', 'yes'),
         ('ask', 'Does the block accept the event?', 'no', 'Nothing runs', 'yes'),
         ('step', "A run starts at the block's script"),
         ('step', 'It executes until the run stops,\nthen returns to the caller')])


def nested_run():
    W, H = 700, 270
    desc = ("A run started inside another. Script A runs on its block. When it moves the party, the move sends the "
            "leave event to the old block, whose script B runs, then the enter event to the new block, whose script "
            "C runs; both run in the middle of the moving instruction. Script A then continues: the party-move "
            "command saved and restores its state. Other commands that send an event start nested runs without "
            "that protection.")
    out = frame(W, H, 'A run inside a run', desc, 'Moving the party starts the scripts of the old and the new block.')
    lanes = [("Script A, on its block", 90), ("Script B, old block", 140), ("Script C, new block", 190)]
    for label, y in lanes:
        out.append(text(150, y, label, 11.5, INK, None, 'end'))
        out.append(f'<line x1="165" y1="{y}" x2="680" y2="{y}" stroke="{GRID}"/>')
    out.append(f'<rect x="170" y="80" width="150" height="20" rx="4" fill="{BLUE}"/>')
    out.append(f'<rect x="520" y="80" width="160" height="20" rx="4" fill="{BLUE}"/>')
    out.append(text(245, 90, 'commands…', 10.5, '#ffffff', None, 'middle'))
    out.append(text(600, 90, 'continues, state restored', 10.5, '#ffffff', None, 'middle'))
    out.append(f'<rect x="320" y="78" width="200" height="24" rx="4" fill="none" stroke="{ORANGE}" stroke-dasharray="4 3"/>')
    out.append(text(420, 70, 'move the party', 11, ORANGE, True, 'middle'))
    out.append(f'<rect x="330" y="130" width="80" height="20" rx="4" fill="{LIGHT}"/>')
    out.append(text(370, 140, 'leave event', 10.5, DARK, None, 'middle'))
    out.append(f'<rect x="425" y="180" width="85" height="20" rx="4" fill="{LIGHT}"/>')
    out.append(text(467, 190, 'enter event', 10.5, DARK, None, 'middle'))
    arrow(out, 'M325,100 L332,128')
    arrow(out, 'M410,150 L428,178')
    arrow(out, 'M510,180 L522,102')
    out.append(text(20, H - 38, 'Only the party-move command saves and restores the running script\'s state; another command', 10.5, INK2))
    out.append(text(20, H - 22, 'that sends an event starts a nested run without that protection.', 10.5, INK2))
    write(OUT, 'scripts-nested-run.svg', out)


def door_steps():
    W, H = 700, 270
    rows = [('Opening a closed door', [3, 4, 5, 6, 7], [3, 3, 3, 3]),
            ('Closing an open door', [7, 6, 5, 4, 3], [4, 4, 4, 5])]
    desc = ('The steps of a door asked to open or close by a script, by wall reference. Opening goes from 3 to 4 at '
            'once, then to 5, 6 and 7 at the door update, with sound 3 at each step. Closing goes from 7 to 6 at '
            'once, then to 5 and 4 with sound 4, and to 3 with sound 5. Steps after the first are at least 6 ticks '
            'apart; the script goes on at once.')
    out = frame(W, H, 'A door moved by a script', desc,
                'Wall references of the leading face; the first step is made at once, the others by the door update.')
    xs = [200, 300, 400, 500, 600]
    for k, (label, refs, sounds) in enumerate(rows):
        y = 100 + k * 80
        out.append(text(20, y, label, 12, INK, True))
        for i, (x, r) in enumerate(zip(xs, refs)):
            end = i in (0, len(refs) - 1)
            out.append(f'<rect x="{x-22}" y="{y-16}" width="44" height="32" rx="6" '
                       f'fill="{BLUE if end else PALE}" stroke="{BLUE}"/>')
            out.append(text(x, y, str(r), 13, '#ffffff' if end else INK, True, 'middle'))
            if i:
                arrow(out, f'M{xs[i-1]+23},{y} L{x-25},{y}')
                out.append(text((xs[i - 1] + x) / 2, y - 12, f'sound {sounds[i-1]}', 9.5, INK2, None, 'middle'))
        out.append(text((xs[0] + xs[1]) / 2, y + 26, 'at once', 10, ORANGE, True, 'middle'))
        for i in range(1, 4):
            out.append(text((xs[i] + xs[i + 1]) / 2, y + 26, '≥ 6 ticks later', 10, INK2, None, 'middle'))
    out.append(text(20, H - 22, 'Three door slots exist; with none free, the door goes to its endpoint at once, without sound.', 10.5, INK2))
    write(OUT, 'scripts-door-steps.svg', out)


def move_targets():
    W, H = 700, 290
    rows = [('The party', 'Set down by the ordinary party move:\nleave and enter events run.'),
            ('Every monster of a block', 'Placed in the destination, with monster\nevents; their direction is overwritten.'),
            ('The items of a block', 'All, or one type; to a block of this or\nanother level. From another level they\nappear when the level is loaded again.')]
    desc = ('The three things a script move can carry. The party is set down in the destination by the ordinary '
            'party move, which runs the leave and enter events. Every monster of a block is placed in the '
            'destination with the monster movement events, and its direction is overwritten. The items of a block, '
            'all of them or those of one type, go to a block of the same or another level; items moved from another '
            'level appear only once the level is loaded again.')
    out = frame(W, H, 'What a script move carries', desc, 'One instruction, three targets, from a block to a destination block.')
    for k, (what, how) in enumerate(rows):
        y = 74 + k * 68
        box(out, 20, y, 180, 54, what, 'state', 12)
        arrow(out, f'M200,{y+27} L240,{y+27}')
        out.append(f'<rect x="244" y="{y}" width="436" height="54" rx="8" fill="{SHADE}" stroke="{BORDER}"/>')
        out.extend(flowcharts.lines(256, y + 27, how, 11, 'start'))
    write(OUT, 'scripts-move-targets.svg', out)


def dialogue():
    flowcharts.chain(
        OUT / 'scripts-dialogue.svg', 'A question in a dialogue',
        'The answer becomes the run variable, which the next conditions test.',
        'How a script uses a dialogue question. The dialogue screen opens with a picture and a text. A question '
        'offers two or three answers labelled with strings of the level; the answer chosen, numbered from 1, '
        'becomes the run variable. A condition then tests the run variable: when it does not hold, the script '
        'jumps to another offset; when it holds, the next command runs. The game loop does not run meanwhile.',
        [('step', 'The dialogue screen: a picture and a text'),
         ('step', 'A question: two or three answers,\nlabelled with strings of the level'),
         ('step', 'The answer chosen, numbered from 1,\nbecomes the run variable'),
         ('ask', 'Does the condition on the run\nvariable hold?', 'no', 'Jump to another offset', 'yes'),
         ('step', 'The next command runs')],
        'Monsters and timed events wait while the player reads and answers.')


# ------------------------------------------------------------- virtual machine
def buffer():
    W, H = 700, 250
    desc = ("The script buffer of a level, 7,508 bytes reused by every level. Its first word is the offset of the "
            "message table. Script code starts at offset 2 and fills the bytes up to the messages, a sequence of "
            "zero-terminated strings; the rest of the buffer is unused. The cell bindings give each scripted block "
            "an offset into the code, and jumps and calls also count from the start of the buffer.")
    out = frame(W, H, 'The script buffer', desc, 'Every offset, in the bindings, jumps and calls, counts from the start of the buffer.')
    y, x0, x1 = 120, 20, 680
    parts = [(x0, 70, 'word 0:\nmessages', BLUE), (90, 440, 'script code, from offset 2', PALE),
             (440, 580, 'message strings', LIGHT), (580, x1, 'unused', SHADE)]
    for a, b, label, fill in parts:
        out.append(f'<rect x="{a}" y="{y}" width="{b-a}" height="40" fill="{fill}" stroke="{BORDER}"/>')
        out.extend(flowcharts.lines((a + b) / 2, y + 20, label, 10.5, 'middle', '#ffffff' if fill == BLUE else INK))
    out.append(text(x0, y + 54, '0', 10, INK2))
    out.append(text(x1, y + 54, '7,508', 10, INK2, None, 'end'))
    arrow(out, f'M45,{y} C45,{y-44} 440,{y-44} 440,{y-2}')
    out.append(text(240, y - 44, 'offset of the messages', 10.5, INK2, None, 'middle'))
    for x, label in [(150, 'a block binding'), (260, 'another binding'), (360, 'a jump or call')]:
        arrow(out, f'M{x},{y+92} L{x},{y+42}')
        out.append(text(x, y + 102, label, 10.5, INK2, None, 'middle'))
    write(VM, 'scripting-buffer.svg', out)


def instruction():
    W, H = 700, 250
    block = 0x016d
    col, row = block % 32, block // 32
    assert (col, row) == (13, 11)
    desc = (f'An example instruction, the bytes fd 6d 01. The command byte fd is SCRIPT_OPEN_DOOR. The two bytes 6d 01 '
            f'are a little-endian word, 0x016d = {block}, the block [{col:02d}:{row:02d}]. Command bytes range from e2 '
            'to ff, thirty commands; a byte below e2 where a command is expected is skipped.')
    out = frame(W, H, 'Reading an instruction', desc, 'A command byte, then its operands; words are little-endian.')
    cells = [('fd', 'command byte'), ('6d', 'low byte'), ('01', 'high byte')]
    for i, (b, label) in enumerate(cells):
        x = 60 + i * 80
        out.append(f'<rect x="{x}" y="84" width="70" height="44" rx="6" fill="{BLUE if i == 0 else PALE}" stroke="{BLUE}"/>')
        out.append(text(x + 35, 106, b, 16, '#ffffff' if i == 0 else INK, True, 'middle'))
        out.append(text(x + 35, 142, label, 10.5, INK2, None, 'middle'))
    out.append(text(320, 96, 'fd = SCRIPT_OPEN_DOOR, 3 bytes', 12, INK))
    out.append(text(320, 116, f'01 6d = 0x016d = {block} = block [{col:02d}:{row:02d}]', 12, INK))
    out.append(text(320, 136, 'the block whose door opens', 10.5, INK2))
    y = 190
    for k in range(32):
        v = 0xe0 + k
        x = 60 + k * 18
        fill = BLUE if v >= 0xe2 else SHADE
        out.append(f'<rect x="{x}" y="{y}" width="16" height="16" rx="2" fill="{fill}"/>')
    out.append(text(60, y + 28, 'e0', 10, INK2))
    out.append(text(60 + 2 * 18, y + 28, 'e2', 10, INK2))
    out.append(text(60 + 31 * 18 + 16, y + 28, 'ff', 10, INK2, None, 'end'))
    out.append(text(60, y - 14, 'Bytes e0 to ff: the 30 command bytes are e2 to ff; a lower byte calls nothing and is skipped.', 10.5, INK2))
    write(VM, 'scripting-instruction.svg', out)


def call_stack():
    W, H = 700, 300
    desc = ('A call and its return. The main script calls a subroutine: the position after the call is saved on the '
            'return stack, which holds ten positions, and the run continues in the subroutine. Its return resumes '
            'at the saved position. A call with a full stack just continues; a return with an empty stack stops '
            'the run; the end command and a level change stop the run and empty the stack.')
    out = frame(W, H, 'A call and its return', desc, 'The return stack holds ten positions and belongs to the program, not to a run.')
    main = ['…', 'call 0x0240', 'next command', '…', 'end']
    sub = ['subroutine at 0x0240', '…', 'return']
    for i, l in enumerate(main):
        y = 84 + i * 30
        out.append(f'<rect x="40" y="{y}" width="170" height="24" rx="4" fill="{PALE if l.startswith("call") else SURF}" stroke="{BORDER}"/>')
        out.append(text(52, y + 12, l, 11, INK))
    for i, l in enumerate(sub):
        y = 114 + i * 30
        out.append(f'<rect x="300" y="{y}" width="170" height="24" rx="4" fill="{PALE if l == "return" else SURF}" stroke="{BORDER}"/>')
        out.append(text(312, y + 12, l, 11, INK))
    arrow(out, 'M210,126 L297,126', 'jump in', 254, 116)
    arrow(out, 'M300,186 C250,186 250,156 213,156', 'resume after the call', 255, 212)
    out.append(text(540, 78, 'Return stack', 12, INK, True))
    for k in range(10):
        y = 90 + k * 18
        out.append(f'<rect x="540" y="{y}" width="130" height="16" rx="2" fill="{LIGHT if k == 9 else SURF}" stroke="{BORDER}"/>')
    out.append(text(605, 90 + 9 * 18 + 8, 'after the call', 10, DARK, None, 'middle'))
    out.append(text(20, H - 38, 'A call with a full stack just continues; a return with an empty stack stops the run;', 10.5, INK2))
    out.append(text(20, H - 22, 'the end command and a level change stop the run and empty the stack.', 10.5, INK2))
    write(VM, 'scripting-call-stack.svg', out)


def decoding():
    assert SCRIPT_BYTES - REACHED == sum(n for _, n in UNREACHED) == 255
    W, H = 700, 230
    share = 100 * REACHED / SCRIPT_BYTES
    desc = (f'The script bytes of the 16 original levels, {SCRIPT_BYTES:,} without the message tables. The decoder '
            f'reaches {REACHED:,}, {share:.1f}%. The 255 bytes it does not reach are '
            + ', '.join(f'{n} of {l}' for l, n in UNREACHED) + '.')
    out = frame(W, H, 'How much of the scripts a decoder reaches', desc,
                'Following the scripts from their entry points, without scanning for command bytes.')
    x0, x1, y = 20, 680, 80
    reach = x0 + (x1 - x0) * REACHED / SCRIPT_BYTES
    out.append(f'<rect x="{x0}" y="{y}" width="{reach - x0:.1f}" height="28" fill="{BLUE}"/>')
    out.append(f'<rect x="{reach:.1f}" y="{y}" width="{x1 - reach:.1f}" height="28" fill="{ORANGE}"/>')
    out.append(text(x0 + 10, y + 14, f'{REACHED:,} bytes reached, {share:.1f}%', 12, '#ffffff', True))
    out.append(text(x1, y + 44, '255 not reached', 10.5, ORANGE, True, 'end'))
    y2 = 150
    xa = x0
    for label, n in UNREACHED:
        w = (x1 - x0) * n / 255
        out.append(f'<rect x="{xa:.1f}" y="{y2}" width="{w:.1f}" height="24" fill="{ORANGE}" fill-opacity="{0.9 if n > 100 else 0.55}" stroke="#ffffff"/>')
        xa += w
    out.append(text(x0 + 6, y2 + 12, f'{UNREACHED[0][1]} after level changes', 11, '#ffffff', True))
    out.append(text(x1, y2 + 38, f'{UNREACHED[1][1]} repeated returns · {UNREACHED[2][1]} in two unreferenced routines', 10.5, INK2, None, 'end'))
    out.append(f'<path d="M{reach:.1f},{y + 28} L{x1},{y2} M{x1},{y + 28} L{x1},{y2}" stroke="{MUTED}" stroke-dasharray="3 3" fill="none"/>')
    out.append(f'<path d="M{reach:.1f},{y + 28} L{x0},{y2}" stroke="{MUTED}" stroke-dasharray="3 3" fill="none"/>')
    write(VM, 'scripting-decoding.svg', out)


if __name__ == '__main__':
    overview()
    block_event()
    nested_run()
    door_steps()
    move_targets()
    dialogue()
    buffer()
    instruction()
    call_stack()
    decoding()
