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

The figures are original schematic drawings. The slot chart reads the four
spell-slot tables from your own DOS START.EXE (data-segment offsets 0x0c05,
0x0c8d, 0x0ccd and 0x0d55, data image at file offset 0x2e360; see
docs/executable/data/PARTY_AND_CHARACTERS.md#d-c05) and stops if they differ from the values
docs/magic/SPELL_SLOTS.md gives. The life of a spell, the states of a slot,
the casting chain and the timeline of a lasting spell transcribe the rules of
README.md, MEMORIZING.md, CASTING.md and LASTING_EFFECTS.md. No game graphics
are read or reproduced.

Usage:
    python3 scripts/magic/make_magic_figures.py [START.EXE] [output_directory]

The defaults are data/originals/eob2/START.EXE and docs/magic/img/.
"""
import hashlib
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

EXE = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'data/originals/eob2/START.EXE'
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else ROOT / 'docs/magic/img'
SHA256 = '2bb5edf06d966a4dbf40dd4866733a9ce37e47c5ace052615df4b6b69d4cb8b4'

data = EXE.read_bytes()
if hashlib.sha256(data).hexdigest() != SHA256:
    sys.exit(f'{EXE}: unexpected SHA-256; this script reads the DOS START.EXE listed in docs/files/INVENTORY.md')
B = 0x2e360


def rows(ds, count):
    return [list(data[B + ds + 8 * r:B + ds + 8 * r + 8]) for r in range(count)]


CLERIC, WISDOM, PALADIN, MAGE = rows(0x0c05, 17), rows(0x0c8d, 8), rows(0x0ccd, 17), rows(0x0d55, 17)

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


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


# ------------------------------------------------------------- the life of a spell
def spell_life():
    W, H = 700, 300
    desc = ('The life of a spell for a character. A mage learns a spell by copying a scroll; a cleric or a paladin '
            'needs no learning. In the memorize or pray menu the player chooses spells, which wait in their '
            'slots. A step of rest makes a waiting spell ready. Casting it from the spell book uses the slot, '
            'and rest makes the used slot ready again. A lasting spell sets an effect and starts a timer; when '
            'the timer expires, the effect ends.')
    out = frame(W, H, 'The life of a spell', desc, 'From the scroll to the expired effect; rest turns used slots back into ready ones.')
    box(out, 20, 84, 100, 46, 'Scroll\n(mages only)', 'end')
    box(out, 155, 84, 105, 46, 'Known spell', 'state')
    box(out, 300, 84, 110, 46, 'Waiting\nin its slot', 'state')
    box(out, 450, 84, 100, 46, 'Ready', 'strong')
    box(out, 590, 84, 90, 46, 'Cast from\nthe book')
    arrow(out, 'M120,107 L152,107', 'copied', 136, 96)
    arrow(out, 'M260,107 L297,107', 'menu', 278, 96)
    arrow(out, 'M410,107 L447,107', 'rest', 428, 96)
    arrow(out, 'M550,107 L587,107', 'cast', 568, 96)
    box(out, 450, 176, 100, 46, 'Used', 'state')
    arrow(out, 'M620,130 L620,199 L553,199')
    out.append(text(590, 212, 'slot used', 10.5, INK2, None, 'middle'))
    arrow(out, 'M500,176 L500,133')
    out.append(text(508, 155, 'rest', 10.5, INK2))
    box(out, 560, 236, 120, 46, 'Lasting effect;\nits timer ends it')
    arrow(out, 'M665,130 L665,233')
    out.append(text(20, 176, 'A cleric or a paladin may choose', 10.5, INK2))
    out.append(text(20, 191, 'any spell of its allowed set;', 10.5, INK2))
    out.append(text(20, 206, 'Turn undead needs no slot.', 10.5, INK2))
    write('magic-spell-life.svg', out)


# ------------------------------------------------------------- slot states
def slot_states():
    W, H = 700, 250
    desc = ('The states of one spell slot. An empty slot receives a spell chosen in the memorize or pray menu and '
            'waits. A step of rest makes a waiting spell ready. Casting it makes it used, and a step of rest '
            'makes it ready again. Removing or clearing a spell in the menu empties its slot, whatever its state. '
            'A waiting spell and a used one are the same value in the slot: a negative spell ID.')
    out = frame(W, H, 'The states of a spell slot', desc,
                'Waiting and used are the same value in the slot: the spell ID made negative.')
    box(out, 20, 100, 120, 44, 'Empty', 'end')
    box(out, 200, 100, 120, 44, 'Waiting', 'state')
    box(out, 380, 100, 120, 44, 'Ready', 'strong')
    box(out, 560, 100, 120, 44, 'Used', 'state')
    arrow(out, 'M140,122 L197,122', 'chosen', 168, 111)
    arrow(out, 'M320,122 L377,122', 'rest', 348, 111)
    arrow(out, 'M500,114 L557,114', 'cast', 528, 103)
    arrow(out, 'M560,132 L503,132', 'rest', 532, 144)
    for x in (260, 440, 620):
        arrow(out, f'M{x},144 L{x},190 L80,190 L80,147' if x == 620 else f'M{x},144 L{x},190', dash=True)
    out.append(text(350, 205, 'removed or cleared in the menu', 10.5, INK2, None, 'middle'))
    out.append(text(20, H - 18, 'The menu changes nothing until it is left; ready copies stay ready if the spell keeps them.', 10.5, INK2))
    write('magic-slot-states.svg', out)


# ------------------------------------------------------------- slot tables
def slot_chart():
    assert MAGE[16] == [5, 5, 5, 5, 5, 3, 3, 2], MAGE[16]
    assert MAGE[0] == [1, 0, 0, 0, 0, 0, 0, 0] and MAGE[11] == [4, 4, 4, 4, 4, 1, 0, 0]
    assert CLERIC[11] == [6, 5, 5, 3, 2, 2, 0, 0] and CLERIC[16] == [7, 7, 7, 7, 5, 3, 2, 0]
    assert PALADIN[8] == [1, 0, 0, 0, 0, 0, 0, 0] and PALADIN[16] == [3, 3, 3, 1, 0, 0, 0, 0]
    assert all(not any(r) for r in PALADIN[:8])
    assert WISDOM[0] == [0] * 8 and WISDOM[7] == [3, 2, 1, 2, 0, 0, 0, 0]
    W, H = 700, 330
    cw, ch = 15, 12
    desc = ('Three grids of spell slots, one row per class level from 1 to 17 and one column per spell level from '
            '1 to 8, darker for more slots. Mages reach 5 slots at spell levels 1 to 5 and their first level-8 slot at '
            'level 16. Clerics reach 7 slots at spell levels 1 to 3 at level 16 and never get level-8 slots. '
            'Paladins get no slot before level 9 and at most 3. Wisdom 13 to 19 adds 1 to 3 bonus slots to a '
            "cleric's lower levels.")
    out = frame(W, H, 'Spell slots by class level', desc,
                'Rows: class level 1 to 17; columns: spell level 1 to 8; the number is the slot count.')
    top = 92
    shades = ['#ffffff', '#e3eefb', '#c9ddf6', '#a9c9f0', '#7fb0ea', '#5596e0', '#2a78d6', '#1c5cab']

    def grid(x, title, table, first=1):
        out.append(text(x, top - 18, title, 12, INK, True))
        for j in range(8):
            out.append(text(x + 28 + j * cw + cw / 2, top - 4, str(j + 1), 9, INK2, None, 'middle'))
        for i, row in enumerate(table):
            y = top + 4 + i * ch
            out.append(text(x + 22, y + ch / 2, str(first + i), 9, INK2, None, 'end'))
            for j, v in enumerate(row):
                out.append(f'<rect x="{x + 28 + j * cw}" y="{y}" width="{cw - 1}" height="{ch - 1}" '
                           f'fill="{shades[min(v, 7)]}" stroke="{GRID}" stroke-width="0.5"/>')
                if v:
                    out.append(text(x + 28 + j * cw + cw / 2 - 0.5, y + ch / 2, str(v), 8.5,
                                    '#ffffff' if v >= 5 else INK, None, 'middle'))
    grid(20, 'Mage', MAGE)
    grid(190, 'Cleric', CLERIC)
    grid(360, 'Paladin', PALADIN)
    grid(530, 'Wisdom bonus', WISDOM[1:], 13)
    out.append(text(530, top + 4 + 7 * ch + 20, 'Wisdom 12 adds nothing; the', 10, INK2))
    out.append(text(530, top + 4 + 7 * ch + 34, 'bonus goes only to levels that', 10, INK2))
    out.append(text(530, top + 4 + 7 * ch + 48, 'already have a slot.', 10, INK2))
    write('magic-slots.svg', out)


# ------------------------------------------------------------- casting
def casting():
    flowcharts.chain(
        OUT / 'magic-casting.svg', 'Casting a spell from the book',
        'The common steps; the definition\'s flags decide which apply.',
        'The steps of a cast from the spell book. The spell is recorded as the last spell cast. A spell that needs '
        'a free hand is refused when both hands are full or one already holds an item of that kind. The slot is '
        'marked used, except for Turn undead, and the cast is announced; the target is chosen when the spell '
        'asks for one, otherwise it is the caster. The sound and the animation play. A spell whose effect is '
        "already active is refused. A timed spell starts its timer, the spell's own routine runs and can stop "
        'the cast, and the lasting effect is set; the defense is recomputed when the flags ask for it. From the '
        'book, the spell book then waits 72 ticks and the party\'s block receives the spell-cast event.',
        [('step', 'Recorded as the last spell cast'),
         ('ask', 'Needs a free hand, and none is free\nor one holds this kind?', 'yes', 'Refused with a message', 'no'),
         ('step', 'Slot marked used (not Turn undead); the cast\nannounced; the target chosen, or the caster'),
         ('step', 'Sound and animation'),
         ('ask', 'Is the effect already active?', 'yes', 'Refused: already under\nthe effect', 'no'),
         ('step', "Timer started; the spell's own routine runs,\nand can stop here"),
         ('step', 'Lasting effect set; defense recomputed;\nportraits redrawn'),
         ('step', 'The book waits 72 ticks; the party\'s block\nreceives the spell-cast event')])


# ------------------------------------------------------------- lasting spell timeline
def lasting():
    W, H = 700, 270
    desc = ('The timeline of a lasting spell. At the cast, the effect bits are set on the target, on the party or on '
            'every living member, and a character timer starts for unit × (base + per level × caster level) '
            "ticks. While it runs, the places of the game that test the bits change. When it expires, the game "
            "prints that the spell expires, runs the spell's end routine and clears the bits. Dispel Magic, "
            'an attack under Invisibility, poison under Slow Poison and the end of the Armor reserve end an '
            'effect earlier.')
    out = frame(W, H, 'The life of a lasting spell', desc,
                'The timer lasts unit × (base + per level × caster level) ticks; a unit is usually 546 ticks.')
    y = 150
    x0, x1 = 110, 590
    out.append(f'<line x1="{x0}" y1="{y}" x2="{x1 + 30}" y2="{y}" stroke="{INK2}" stroke-width="1.4" marker-end="url(#ah)"/>')
    out.append(text(x1 + 34, y - 10, 'ticks', 10, INK2, None, 'end'))
    out.append(f'<rect x="{x0}" y="{y - 26}" width="{x1 - x0}" height="20" rx="4" fill="{LIGHT}"/>')
    out.append(text(x0 + 10, y - 16, 'effect bits set: hit rolls, defense, hands, sight… change', 11, DARK))
    for x, label1, label2 in [(x0, 'Cast', 'bits set, timer started'), (x1, 'Timer expires', 'end routine, bits cleared')]:
        out.append(f'<circle cx="{x}" cy="{y}" r="6" fill="{BLUE}"/>')
        out.append(text(x, y + 22, label1, 12, INK, True, 'middle'))
        out.append(text(x, y + 38, label2, 10.5, INK2, None, 'middle'))
    xe = 470
    out.append(f'<line x1="{xe}" y1="{y - 36}" x2="{xe}" y2="{y + 8}" stroke="{ORANGE}" stroke-width="2" stroke-dasharray="4 3"/>')
    out.append(text(xe, y - 74, 'or earlier', 12, ORANGE, True, 'middle'))
    out.append(text(xe, y - 58, 'Dispel Magic, an attack under Invisibility,', 10.5, INK2, None, 'middle'))
    out.append(text(xe, y - 44, 'poison under Slow Poison, Armor used up', 10.5, INK2, None, 'middle'))
    out.append(text(20, H - 22, 'The bits and the timers are saved with the characters and the party: an effect survives a saved game.', 10.5, INK2))
    write('magic-lasting.svg', out)


if __name__ == '__main__':
    spell_life()
    slot_states()
    slot_chart()
    casting()
    lasting()
