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

The figures are original schematic drawings. The experience chart reads the
level thresholds from your own DOS START.EXE (far-pointer table at
data-segment offset 0x344a, data image at file offset 0x2e360; see
docs/executable/data/PARTY_AND_CHARACTERS.md#d-344a); the starting-items diagram transcribes the item
choices of the party setup (overlay physical offsets 0x4235a-0x4262d and the
armour records at file offset 0x27560; see
docs/executable/overlays/OVERLAY_246.md#o-4235a),
with the names of the ITEM.DAT template items; the melee-target diagram
reads the close-attack tables at data-segment offsets 0x3086-0x30e5 (see
docs/executable/data/MONSTERS.md#d-3086); the modifier chart reads the dexterity defense
words at 0x32e8 and the constitution bytes at 0x3319 (data/PARTY_AND_CHARACTERS.md#d-3319); the
experience chart the same thresholds as above; the condition figure follows
docs/party/CONDITIONS.md. No game graphics are used.

Usage:
    python3 scripts/party/make_party_figures.py [START.EXE] [output_directory]

The defaults are data/originals/eob2/START.EXE and docs/party/img/.
"""
import hashlib
import math
import sys
from html import escape
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
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/party/img'
SHA256 = '2bb5edf06d966a4dbf40dd4866733a9ce37e47c5ace052615df4b6b69d4cb8b4'

d = EXE.read_bytes()
if hashlib.sha256(d).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 dword(o):
    return int.from_bytes(d[B + o:B + o + 4], 'little', signed=True)


def table(t):
    """Experience thresholds of base type t (levels 1-13)."""
    off = int.from_bytes(d[B + 0x344a + 4 * t:B + 0x344c + 4 * t], 'little')
    return [dword(off + 4 * i) for i in range(13)]


FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
SURF, BORDER, INK, INK2, GRID = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#eeede9'
BLUE, ORANGE, HEAD, SHADE = '#2a78d6', '#eb6834', '#1c5cab', '#f1f0ec'
TRACK = ('#e9e8e4', '#dedcd6')


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


# ---------------------------------------------------------------- chart
def experience_chart():
    W, H = 700, 450
    x0, x1, vmax = 130, 560, 160000
    X = lambda v: x0 + (x1 - x0) * min(v, vmax) / vmax
    rows = [('Fighter', 0, True, True), ('Mage', 1, True, True),
            ('Cleric', 2, True, True), ('Thief', 3, True, True),
            ('Paladin, ranger', 4, True, False)]
    start = 69000
    shares = (34500, 23000)
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" font-family="{FONT}">',
           '<title>Where the starting experience falls on each level ladder</title>',
           '<desc>For each base class, a bar divided into its levels from 0 to 160,000 experience points. '
           'The level reached with 69,000 points is highlighted: 7 for fighter, mage, cleric and thief, 6 for paladin and ranger. '
           'Orange dots mark 34,500 and 23,000 points, the share of each class in a combined class of two or three classes. '
           'A column gives the points a single-class character still needs for the next level: fighter 56,001, mage 21,001, '
           'cleric 41,001, thief 1,001, paladin or ranger 6,001.</desc>',
           f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>',
           text(20, 26, 'Where the starting experience falls on each level ladder', 14, weight=True),
           text(20, 46, '69,000 points divided by the number of classes; each bar shows the levels of one base class.', 12, INK2)]
    # legend
    ly = 70
    out.append(f'<rect x="20" y="{ly-7}" width="22" height="14" rx="2" fill="{BLUE}"/>')
    out.append(text(48, ly, 'Level at 69,000 (single class)', 12, INK))
    out.append(f'<circle cx="31" cy="{ly+20}" r="5" fill="{ORANGE}" stroke="{SURF}" stroke-width="2"/>')
    out.append(text(48, ly + 20, 'Share of one class in a combined class: 34,500 (two classes) or 23,000 (three)', 12, INK))
    top, rh, gap = 150, 26, 18
    bottom = top + len(rows) * (rh + gap) - gap
    # grid and axis
    for v in range(0, vmax + 1, 20000):
        out.append(f'<line x1="{X(v):.1f}" y1="{top-6}" x2="{X(v):.1f}" y2="{bottom+6}" stroke="{GRID}" stroke-width="1"/>')
        out.append(text(X(v), bottom + 20, f'{v:,}', 11, INK2, anchor='middle'))
    out.append(text((x0 + x1) / 2, bottom + 38, 'Experience points', 11, INK2, anchor='middle'))
    # reference lines and their labels
    refs = [(23000, '23,000', 'three classes', 'end'), (34500, '34,500', 'two classes', 'start'),
            (69000, '69,000', 'one class', 'start')]
    for v, a, b, anc in refs:
        x = X(v)
        out.append(f'<line x1="{x:.1f}" y1="{top-30}" x2="{x:.1f}" y2="{bottom+6}" stroke="{INK2}" stroke-width="1" stroke-dasharray="3 3"/>')
        tx = x - 4 if anc == 'end' else x + 4
        out.append(text(tx, top - 26, a, 11, INK, True, anc))
        out.append(text(tx, top - 13, b, 11, INK2, anchor=anc))
    # right column
    out.append(text(W - 20, top - 26, 'Single class:', 11, INK, True, 'end'))
    out.append(text(W - 20, top - 13, 'points to next level', 11, INK2, anchor='end'))
    for k, (name, t, has2, has3) in enumerate(rows):
        y = top + k * (rh + gap)
        thr = table(t)
        out.append(text(x0 - 12, y + rh / 2, name, 13, INK, anchor='end'))
        lvl_start = max(L for L in range(1, 14) if thr[L - 1] <= start)
        for L in range(1, 14):
            a = thr[L - 1]
            b = thr[L] if L < 13 else 10**9
            if a >= vmax:
                break
            xa, xb = X(a), X(b)
            clipped = b > vmax
            ra, rb = xa + 1, (xb if clipped else xb - 1)
            if rb - ra < 0.5:
                continue
            hi = (L == lvl_start)
            fill = BLUE if hi else TRACK[L % 2]
            out.append(f'<rect x="{ra:.1f}" y="{y}" width="{rb-ra:.1f}" height="{rh}" rx="2" fill="{fill}"/>')
            if rb - ra >= 14:
                out.append(text((ra + rb) / 2, y + rh / 2, str(L), 11, '#ffffff' if hi else INK2, True, 'middle'))
        for v, ok in ((shares[0], has2), (shares[1], has3)):
            if ok:
                out.append(f'<circle cx="{X(v):.1f}" cy="{y-1}" r="5" fill="{ORANGE}" stroke="{SURF}" stroke-width="2"/>')
        nxt = thr[lvl_start] - start + 1
        out.append(text(W - 20, y + rh / 2, f'+{nxt:,}', 13, INK, True, 'end'))
    out.append(text(20, H - 34, 'Levels are read from a separate table; they agree with these totals.', 11, INK2))
    out.append(text(20, H - 18, 'A level is gained once experience is strictly above the next threshold.', 11, INK2))
    out.append('</svg>')
    return '\n'.join(out) + '\n'


# ---------------------------------------------------------------- items
def items_diagram():
    W = 700
    out = []
    y = 0
    groups = [
        ('Fighter, ranger or paladin', 'component (9 classes)', 'Armour, one of three',
         [('Plate Mail', None), ('Scale Mail (1)', '+ Shield'), ('Chainmail (1)', '+ Shield (1)')],
         'Weapon', [('Dwarf: Axe (1)', None), ('Others, one of two:', 'Short sword (1) or Long Sword')]),
        ('MAGE', 'only', 'Armour', [('Robe', None)],
         'Weapon, one of two', [('Staff', None), ('Dagger (1)', None)]),
        ('CLERIC, CLERIC/THIEF,', 'CLERIC/MAGE', 'Armour, one of two',
         [('Scale Mail (1)', '+ Shield'), ('Chainmail (1)', '+ Shield')],
         'Weapon', [('Mace, value 0 or 1', 'one of two')]),
        ('THIEF, THIEF/MAGE', '', 'Armour, one of two',
         [('Leather armor (1)', '+ Shield (1)'), ('Leather armor', '+ Shield (2)')],
         'Weapon', [('Dwarf: Axe (1)', None), ('Others: Short sword (1)', None)]),
    ]
    pad, cg = 20, 10
    cw = (W - 2 * pad - cg) / 2
    body = []
    body.append(text(20, 26, 'How a new character’s starting items are chosen', 14, weight=True))
    body.append(text(20, 46, 'Each step applies to every character in turn; the random choices are rolled for each one.', 12, INK2))
    y = 72
    body.append(text(20, y, '1. Armour and weapon, by class group', 13, INK, True))
    y += 16

    def chip(x, yy, w, a, b):
        h = 34 if b else 22
        s = [f'<rect x="{x:.1f}" y="{yy:.1f}" width="{w:.1f}" height="{h}" rx="4" fill="#f1f0ec"/>']
        if b:
            s.append(text(x + 8, yy + 10, a, 11.5, INK))
            s.append(text(x + 8, yy + 24, b, 11.5, INK2))
        else:
            s.append(text(x + 8, yy + 11, a, 11.5, INK))
        return s, h

    card_h = 0
    cards = []
    for i, (h1, h2, al, aopts, wl, wopts) in enumerate(groups):
        x = pad + (i % 2) * (cw + cg)
        c = []
        yy = y + (i // 2) * 1000          # second row placed below, shifted afterwards
        c.append(f'<rect x="{x:.1f}" y="{yy:.1f}" width="{cw:.1f}" height="@H@" rx="6" fill="#ffffff" stroke="{BORDER}"/>')
        c.append(f'<path d="M{x:.1f},{yy+6:.1f} a6,6 0 0 1 6,-6 h{cw-12:.1f} a6,6 0 0 1 6,6 v34 h{-cw:.1f} z" fill="{HEAD}"/>')
        c.append(text(x + 10, yy + 13, h1, 12, '#ffffff', True))
        if h2:
            c.append(text(x + 10, yy + 29, h2, 11.5, '#ffffff'))
        yy += 52
        for lab, opts in ((al, aopts), (wl, wopts)):
            c.append(text(x + 10, yy, lab.upper(), 10, INK2, True))
            yy += 10
            for a, b in opts:
                s, h = chip(x + 8, yy, cw - 16, a, b)
                c += s
                yy += h + 4
            yy += 12
        card_h = max(card_h, yy - y - (i // 2) * 1000)
        cards.append(c)
    import re as _re
    for i, c in enumerate(cards):
        shift = (i // 2) * (card_h + cg - 1000)
        def move(m):
            return f'{m.group(1)}="{float(m.group(2)) + shift:.1f}"'
        for part in c:
            part = part.replace('@H@', f'{card_h - 4:.1f}')
            if shift:
                part = _re.sub(r'\b(y|y1|y2|cy)="([-0-9.]+)"', move, part)
                part = _re.sub(r'M([-0-9.]+),([-0-9.]+)', lambda m: f'M{m.group(1)},{float(m.group(2)) + shift:.1f}', part)
            body.append(part)
    y += 2 * card_h + cg + 18

    body.append(text(20, y, '2. For everyone', 13, INK, True))
    y += 14
    s, h = chip(pad, y, W - 2 * pad, 'Two Iron Rations and a Potion (2)', None)
    body += s
    y += h + 22

    body.append(text(20, y, '3. Extras for each class component', 13, INK, True))
    y += 14
    extras = [('Mage component', 'Spellbook, mage scrolls of', 'Magic Missile and Fireball'),
              ('Cleric or paladin component', 'Cleric Holy symbol (PALADIN: Paladin’s', 'Holy Symbol), and a Scroll (49)'),
              ('Thief component', 'Lock picks', None)]
    ew = (W - 2 * pad - 2 * cg) / 3
    for i, (h1, a, b) in enumerate(extras):
        x = pad + i * (ew + cg)
        body.append(f'<rect x="{x:.1f}" y="{y:.1f}" width="{ew:.1f}" height="64" rx="6" fill="#ffffff" stroke="{BORDER}"/>')
        body.append(text(x + 10, y + 14, h1, 12, HEAD, True))
        body.append(text(x + 10, y + 34, a, 11.5, INK))
        if b:
            body.append(text(x + 10, y + 50, b, 11.5, INK))
    y += 64 + 22

    body.append(text(20, y, '4. The character in the first box', 13, INK, True))
    y += 14
    s, h = chip(pad, y, W - 2 * pad, 'Khelben’s Coin', None)
    body += s
    y += h + 24
    body.append(text(20, y, '(n): value given to the item; what it means for armour and weapons is not established.', 11, INK2))
    y += 16
    body.append(text(20, y, 'Names are those of the ITEM.DAT template items.', 11, INK2))
    y += 12
    H = int(y + 12)
    out.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" font-family="{FONT}">')
    out.append('<title>How a new character’s starting items are chosen</title>')
    out.append('<desc>Step 1, by class group: a character with a fighter, ranger or paladin component gets one of Plate Mail, Scale Mail with a Shield, or Chainmail with a Shield, '
               'and an Axe if a dwarf, otherwise a Short sword or a Long Sword. A MAGE gets a Robe and a Staff or a Dagger. '
               'CLERIC, CLERIC/THIEF and CLERIC/MAGE get Scale Mail or Chainmail with a Shield, and a Mace. '
               'THIEF and THIEF/MAGE get Leather armor with a Shield, and an Axe if a dwarf, otherwise a Short sword. '
               'Step 2: everyone gets two Iron Rations and a Potion. Step 3: a mage component adds a Spellbook and two mage scrolls, '
               'a cleric or paladin component a holy symbol and a scroll, a thief component Lock picks. Step 4: the first character gets Khelben’s Coin.</desc>')
    out.append(f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>')
    out += body
    out.append('</svg>')
    return '\n'.join(out) + '\n'


# ---------------------------------------------------------------- melee targets
def melee_targets():
    """Attack orders of a monster's close attack, from DS:0x3086 (positions
    that can attack), DS:0x3096 (group by facing), DS:0x30a6 (two orders of
    six slots per group) and DS:0x30d6 (which order a position uses)."""
    chk1 = list(d[B + 0x3086:B + 0x3096])
    group = list(d[B + 0x3096:B + 0x30a6])
    orders = list(d[B + 0x30a6:B + 0x30d6])
    half = list(d[B + 0x30d6:B + 0x30e6])
    W, H = 700, 370
    BS = 76                      # block size
    col_w, top = 168, 104
    x_start = (W - 4 * col_w) / 2
    # party faces north (direction 0); monster block offset and facing
    cols = [('Monster in front', (0, -1), 2), ('Monster on the left', (-1, 0), 1),
            ('Monster on the right', (1, 0), 3), ('Monster behind', (0, 1), 0)]
    ords = ['1st', '2nd', '3rd', '4th', '5th', '6th']
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" font-family="{FONT}">',
           '<title>Which character a monster attacks</title>',
           '<desc>Eight diagrams of the party block, front rank at the top, next to the block of an attacking monster. '
           'For each side the monster can attack from and each of its two attacking positions, the six party slots are numbered '
           'in the order the game tries them; the first eligible character is attacked. A monster in front attacks first the '
           'front character on its side, a monster on a side the character of that side nearest to it, a monster behind the back '
           'character on its side.</desc>',
           f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{SURF}" stroke="{BORDER}"/>',
           text(20, 26, 'Which character a monster attacks', 14, weight=True),
           text(20, 46, 'Party facing up, front rank at the top; the slots are tried in this order.', 12, INK2)]

    def block(x, y):
        return f'<rect x="{x:.1f}" y="{y:.1f}" width="{BS}" height="{BS}" rx="4" fill="#ffffff" stroke="{BORDER}"/>'

    def party(x, y, order):
        s = [block(x, y)]
        cw, ch, g = 33, 21, 3
        ox, oy = x + (BS - 2 * cw - g) / 2, y + (BS - 3 * ch - 2 * g) / 2
        for slot in range(6):
            k = order.index(slot)
            cx, cy = ox + (slot % 2) * (cw + g), oy + (slot // 2) * (ch + g)
            fill = BLUE if k == 0 else '#f1f0ec'
            s.append(f'<rect x="{cx:.1f}" y="{cy:.1f}" width="{cw}" height="{ch}" rx="3" fill="{fill}"/>')
            s.append(text(cx + cw / 2, cy + ch / 2, ords[k], 10, '#ffffff' if k == 0 else INK, k == 0, 'middle'))
        return s

    def monster(x, y, pos):
        qx, qy = x + (BS / 4 if pos in (0, 2) else 3 * BS / 4), y + (BS / 4 if pos in (0, 1) else 3 * BS / 4)
        return [block(x, y),
                f'<line x1="{x + BS/2:.1f}" y1="{y:.1f}" x2="{x + BS/2:.1f}" y2="{y + BS:.1f}" stroke="{GRID}"/>',
                f'<line x1="{x:.1f}" y1="{y + BS/2:.1f}" x2="{x + BS:.1f}" y2="{y + BS/2:.1f}" stroke="{GRID}"/>',
                f'<circle cx="{qx:.1f}" cy="{qy:.1f}" r="9" fill="{ORANGE}" stroke="{SURF}" stroke-width="2"/>']

    for c, (title, (dx, dy), mdir) in enumerate(cols):
        cx0 = x_start + c * col_w
        out.append(text(cx0 + col_w / 2, top - 22, title, 12, INK, True, 'middle'))
        g = group[mdir]                       # party direction 0
        positions = [p for p in range(4) if chk1[(mdir << 2) + p]]
        for i, p in enumerate(positions):
            v = half[(mdir << 2) + p]
            order = orders[g * 12 + (6 if v else 0):g * 12 + (6 if v else 0) + 6]
            if dy:                              # monster above or below: panels side by side
                px = cx0 + i * (BS + 8) + (col_w - 2 * BS - 8) / 2
                if dy < 0:
                    my, py = top, top + BS + 8
                else:
                    py, my = top, top + BS + 8
                out += monster(px, my, p)
                out += party(px, py, order)
            else:                               # monster left or right: panels stacked
                py = top + i * (BS + 8)
                if dx < 0:
                    mx, px = cx0 + (col_w - 2 * BS - 8) / 2, cx0 + (col_w - 2 * BS - 8) / 2 + BS + 8
                else:
                    px, mx = cx0 + (col_w - 2 * BS - 8) / 2, cx0 + (col_w - 2 * BS - 8) / 2 + BS + 8
                out += monster(mx, py, p)
                out += party(px, py, order)
    ly = top + 2 * BS + 8 + 34
    out.append(f'<circle cx="30" cy="{ly}" r="7" fill="{ORANGE}" stroke="{SURF}" stroke-width="2"/>')
    out.append(text(44, ly, 'The monster, in the half of its block that can attack', 12, INK))
    out.append(f'<rect x="470" y="{ly-9}" width="30" height="18" rx="3" fill="{BLUE}"/>')
    out.append(text(508, ly, 'First character tried', 12, INK))
    out.append(text(20, ly + 26, 'Absent, dead and petrified characters are skipped; an invisible one is skipped 4 times in 5.', 12, INK2))
    out.append(text(20, ly + 44, 'A monster in the centre of its block uses one of its two orders at random.', 12, INK2))
    out.append('</svg>')
    return '\n'.join(out) + '\n'


# ---------------------------------------------------------------- shared frame
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}" 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 num(v):
    return f'−{-v}' if v < 0 else (f'+{v}' if v > 0 else '0')


# ---------------------------------------------------------------- attribute modifiers
DEX_DEFENSE = [int.from_bytes(d[B + 0x32e8 + 2 * i:B + 0x32ea + 2 * i], 'little', signed=True) for i in range(25)]
CON_HP = [int.from_bytes(d[B + 0x3319 + i:B + 0x331a + i], 'little', signed=True) for i in range(25)]


def attribute_modifiers():
    W, H = 700, 352
    x0, x1 = 70, 680
    X = lambda sc: x0 + (x1 - x0) * (sc - 0.5) / 24
    desc = ('Two modifiers by attribute score, from 1 to 24. Dexterity changes the starting defense: '
            + ', '.join(f'{num(DEX_DEFENSE[i])} at {i}' for i in (1, 6, 7, 15, 18, 20, 23)) +
            '; a lower defense makes monsters miss more often. Constitution changes the hit points gained with each '
            'level: ' + ', '.join(f'{num(CON_HP[i])} at {i}' for i in (1, 4, 7, 15, 18, 20, 23)) +
            '; above +2 only for fighters, paladins and rangers.')
    out = frame(W, H, 'Dexterity and constitution modifiers', desc, 'By score; the dexterity table and the constitution table of START.EXE.')
    top, ph = 96, 170
    vmin, vmax = -6, 7
    Y = lambda v: top + ph * (vmax - v) / (vmax - vmin)
    for v in range(vmin, vmax + 1):
        if v % 2 == 0:
            out.append(f'<line x1="{x0}" y1="{Y(v):.1f}" x2="{x1}" y2="{Y(v):.1f}" stroke="{INK2 if v == 0 else GRID}"/>')
            out.append(text(x0 - 8, Y(v), num(v), 11, INK2, anchor='end'))
    for sc in range(1, 25):
        out.append(text(X(sc), top + ph + 14, str(sc), 10, INK2, anchor='middle'))
    for values, colour, dash in ((DEX_DEFENSE, BLUE, ''), (CON_HP, ORANGE, ' stroke-dasharray="6 3"')):
        pts = ' '.join(f'{X(sc):.1f},{Y(values[sc]):.1f}' for sc in range(1, 25))
        out.append(f'<polyline points="{pts}" fill="none" stroke="{colour}" stroke-width="2"{dash}/>')
        for sc in range(1, 25):
            out.append(f'<circle cx="{X(sc):.1f}" cy="{Y(values[sc]):.1f}" r="3" fill="{colour}"/>')
    ly = top + ph + 40
    out.append(f'<line x1="20" y1="{ly}" x2="48" y2="{ly}" stroke="{BLUE}" stroke-width="2"/>')
    out.append(text(54, ly, 'Dexterity: added to the starting defense of 10', 12))
    out.append(f'<line x1="360" y1="{ly}" x2="388" y2="{ly}" stroke="{ORANGE}" stroke-width="2" stroke-dasharray="6 3"/>')
    out.append(text(394, ly, 'Constitution: hit points per level', 12))
    out.append(text(20, ly + 22, 'A lower defense is better. Constitution bonuses above +2 count only for fighters, paladins and rangers.', 11, INK2))
    out.append('</svg>')
    return '\n'.join(out) + '\n'


# ---------------------------------------------------------------- experience thresholds
def experience_thresholds():
    W, H = 700, 360
    rows = [('Fighter', 0, BLUE, ''), ('Mage', 1, ORANGE, '6 3'), ('Cleric', 2, '#2f8f5b', '2 3'),
            ('Thief', 3, '#8a4fc7', '9 3 2 3'), ('Paladin, ranger', 4, INK2, '1 4')]
    x0, x1, top, ph = 80, 560, 80, 220
    lo, hi = 3, math.log10(2_000_000)
    X = lambda L: x0 + (x1 - x0) * (L - 2) / 11
    Y = lambda v: top + ph * (hi - math.log10(v)) / (hi - lo)
    desc = ('Experience needed for each level from 2 to 13, by base class, on a logarithmic scale. ' +
            '; '.join(f'{n}: {table(t)[1]:,} for level 2, {table(t)[12]:,} for level 13' for n, t, _, _ in rows) +
            '. Level 13 is the highest that experience can reach.')
    out = frame(W, H, 'Experience needed for each level', desc, 'Logarithmic scale; a class gains a level when its experience is strictly above the threshold.')
    for v in (1_000, 10_000, 100_000, 1_000_000):
        out.append(f'<line x1="{x0}" y1="{Y(v):.1f}" x2="{x1}" y2="{Y(v):.1f}" stroke="{GRID}"/>')
        out.append(text(x0 - 8, Y(v), f'{v:,}', 11, INK2, anchor='end'))
    for L in range(2, 14):
        out.append(text(X(L), top + ph + 14, str(L), 11, INK2, anchor='middle'))
    out.append(text((x0 + x1) / 2, top + ph + 32, 'Level', 11, INK2, anchor='middle'))
    for k, (name, t, colour, dash) in enumerate(rows):
        thr = table(t)
        pts = ' '.join(f'{X(L):.1f},{Y(thr[L-1]):.1f}' for L in range(2, 14))
        da = f' stroke-dasharray="{dash}"' if dash else ''
        out.append(f'<polyline points="{pts}" fill="none" stroke="{colour}" stroke-width="2.2"{da}/>')
        ly = top + 16 + k * 26
        out.append(f'<line x1="{x1+20}" y1="{ly}" x2="{x1+46}" y2="{ly}" stroke="{colour}" stroke-width="2.2"{da}/>')
        out.append(text(x1 + 52, ly, name, 12))
    out.append('</svg>')
    return '\n'.join(out) + '\n'


# ---------------------------------------------------------------- conditions
def conditions():
    W, H = 700, 250
    desc = ('A character\'s condition by hit points: above 0 it is conscious; from 0 to −9 it is unconscious and can '
            'no longer use its hands or eat; at −10 or less it is dead. Three status conditions come on top: poisoned, '
            'which still allows everything; paralyzed, which stops the use of hand items; turned to stone, which '
            'stops everything, and which monsters skip when they choose whom to attack.')
    out = frame(W, H, 'A character\'s condition', desc, 'Hit points set the state; three status conditions come on top.')
    x0, x1, y = 40, 660, 110
    segs = [('Conscious', 'above 0 hit points', 0.5, '#dbe8f8', BLUE),
            ('Unconscious', '0 to −9', 0.25, '#fdf0ea', ORANGE),
            ('Dead', '−10 or less', 0.25, SHADE, INK2)]
    x = x0
    for label, sub, frac, fill, ink in segs:
        w = (x1 - x0) * frac
        out.append(f'<rect x="{x:.1f}" y="{y}" width="{w-4:.1f}" height="54" rx="8" fill="{fill}" stroke="{ink}"/>')
        out.append(text(x + 14, y + 19, label, 13, ink, True))
        out.append(text(x + 14, y + 38, sub, 11.5, INK2))
        x += w
    out.append(text(x0, y - 18, 'Hit points', 11, INK2, True))
    out.append(text(x1, y - 18, 'fewer', 11, INK2, anchor='end'))
    flags = [('Poisoned', 'can still do everything'), ('Paralyzed', 'cannot use hand items'),
             ('Turned to stone', 'nothing; monsters skip it')]
    for i, (label, sub) in enumerate(flags):
        fx = x0 + i * 212
        out.append(f'<rect x="{fx}" y="{y+76}" width="200" height="44" rx="8" fill="{SURF}" stroke="{BORDER}"/>')
        out.append(text(fx + 12, y + 92, label, 12, INK, True))
        out.append(text(fx + 12, y + 109, sub, 10.5, INK2))
    out.append('</svg>')
    return '\n'.join(out) + '\n'


OUT.mkdir(parents=True, exist_ok=True)
assert DEX_DEFENSE[1:25] == [5, 5, 4, 3, 2, 1] + [0] * 8 + [-1, -2, -3, -4, -4, -5, -5, -5, -6, -6]
assert CON_HP[1:25] == [-3, -2, -2, -1, -1, -1] + [0] * 8 + [1, 2, 3, 4, 5, 6, 6, 6, 7, 7]
(OUT / 'party-starting-experience.svg').write_text(experience_chart())
(OUT / 'party-starting-items.svg').write_text(items_diagram())
(OUT / 'party-melee-targets.svg').write_text(melee_targets())
(OUT / 'party-attribute-modifiers.svg').write_text(attribute_modifiers())
(OUT / 'party-experience-thresholds.svg').write_text(experience_thresholds())
(OUT / 'party-conditions.svg').write_text(conditions())
# ------------------------------------------------------------- decision chains
sys.path[:0] = [str(Path(__file__).resolve().parent), str(ROOT / 'scripts/common')]
import flowcharts  # noqa: E402

flowcharts.chain(
    OUT / 'party-recruiting.svg', 'Recruiting a character',
    'A prepared character joins by a dialogue, special event 4 or a resurrection.',
    'How a prepared character joins the party. When six characters are present, the player chooses one to '
    'dismiss, or CANCEL, which changes nothing. The bones of the newcomer are deleted and the chosen character, '
    'if any, is dismissed; the preset is copied into the first free slot; its defense is computed again, its '
    'items are copied and its portrait is drawn.',
    [('step', 'A dialogue, special event 4\nor a resurrection'),
     ('ask', 'Are six characters present?', 'yes',
      'The player chooses one to dismiss;\nCANCEL changes nothing', 'no, or one chosen'),
     ('step', 'Its bones deleted; the chosen\ncharacter, if any, dismissed'),
     ('step', 'The preset copied into the first free slot'),
     ('step', 'Defense computed again; items\ncopied; portrait drawn')])
flowcharts.chain(
    OUT / 'party-insal-leaves.svg', 'Insal leaves the party',
    'After a long rest, when Insal is with at least four others.',
    'What happens at the end of a rest of more than four hours that ends without monsters or defeat. If Insal '
    'is living and at least five characters are present, Insal leaves the party and a back character fills '
    'the slot; two global flags are cleared; swords, rations, potions and rings are taken; a parchment is left '
    "in the party's block; two messages are shown. Otherwise nothing happens.",
    [('step', 'A rest of more than four hours ends\nwithout monsters or defeat'),
     ('ask', 'Is Insal living, with at least\nfive characters present?', 'no', 'Nothing happens', 'yes'),
     ('step', 'Insal leaves the party;\na back character fills the slot'),
     ('step', 'Two global flags cleared; swords,\nrations, potions and rings taken'),
     ('step', "A parchment left in the party's\nblock; two messages")])
flowcharts.chain(
    OUT / 'party-rolling-attributes.svg', 'Rolling an attribute',
    'Each attribute of a new character, from the dice to its final value.',
    'How an attribute of a new character is rolled. Four six-sided dice are rolled and the best three kept; '
    'the race modifier is added; the value is raised to the minimum of the class and race. A strength of 18 '
    "also gets a percentage, 1d100. In both cases the value is then lowered to the race's maximum.",
    [('step', '4d6, keeping the best three'),
     ('step', 'Plus the race modifier'),
     ('step', 'Raised to the minimum of the class\nand the race'),
     ('ask', 'Is it strength, at 18?', 'yes', 'A percentage is rolled: 1d100', 'in both cases'),
     ('step', "Lowered to the race's maximum")])
flowcharts.chain(
    OUT / 'party-transfer-items.svg', 'Converting a transferred item',
    'Each item of the four transferred characters, one at a time.',
    'How an item of a transferred character is converted. If its type does not pass the filter, it is '
    'dropped. Otherwise a copy of item 1 takes the flags, icon, type and value of the old item; the value is '
    'converted for scrolls, potions and wands; if an item of this game matches it, the item is carried with '
    "that item's names; if none does, a matching failure message is shown and the item is dropped.",
    [('step', 'An item of a transferred character'),
     ('ask', 'Does its type pass the filter?', 'no', 'Dropped', 'yes'),
     ('step', 'A copy of item 1: flags, icon, type\nand value of the old item'),
     ('step', 'Value converted for scrolls,\npotions and wands'),
     ('ask', 'Does an item of this game\nmatch it, for its names?', 'no',
      'Matching failure message;\ndropped', 'yes'),
     ('step', "Carried, with that item's names")])
flowcharts.chain(
    OUT / 'party-transfer.svg', 'Transferring a party',
    'From the start menu to a new game on level 4.',
    'How a party is transferred from Eye of the Beholder I. The option TRANSFER EOB I PARTY looks for '
    'EOBDATA.SAV; if it is missing, the player may look again or go back to the start menu. The game reads the '
    'file and converts its six characters; the player chooses four present characters, or CANCEL, back to the '
    "start menu. The four move to slots 0 to 3, their items are converted, Khelben's Coin goes to the first "
    'with an empty backpack slot, and a new game starts on level 4.',
    [('step', 'TRANSFER EOB I PARTY'),
     ('ask', 'Is EOBDATA.SAV found?', 'no', 'Look again, or back to\nthe start menu', 'yes'),
     ('step', 'Read it; convert the six characters'),
     ('ask', 'Choose four present characters', 'CANCEL', 'Back to the start menu', 'OK with four'),
     ('step', 'The four move to slots 0 to 3;\ntheir items are converted'),
     ('step', "Khelben's Coin to the first with an\nempty backpack slot"),
     ('step', 'A new game on level 4')])


def creation_screens():
    """The screens of party creation, transcribed from docs/party/CREATING_A_PARTY.md."""
    from html import escape as esc
    T, L = flowcharts.text, flowcharts.lines
    W, H = 700, 400
    INK2_, BLUE_, PALE_, BORDER_ = flowcharts.INK2, flowcharts.BLUE, flowcharts.PALE, flowcharts.BORDER
    desc = ('The screens of party creation. START A NEW PARTY on the start menu leads to the party screen of four '
            'boxes. A filled box shows the character, which can be viewed or deleted. An empty box starts a '
            'character: race and sex, then a class allowed by the race and the party, then an alignment allowed '
            'by the class and the party; the class and alignment menus can go back one step. Attributes, levels '
            'and hit points are rolled and shown on the stats screen, where the player can reroll, modify a value '
            'within its limits or choose a portrait; keeping the character leads to its name, then back to the '
            'party screen. PLAY, with four characters, enters the game: status, food, items and spells.')
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" '
           f'font-family="{flowcharts.FONT}">', f'<title>The screens of party creation</title>',
           f'<desc>{esc(desc)}</desc>',
           f'<rect x="0.5" y="0.5" width="{W-1}" height="{H-1}" rx="10" fill="{flowcharts.SURF}" stroke="{BORDER_}"/>',
           T(20, 26, 'The screens of party creation', 14, weight=True),
           T(20, 46, 'From the start menu to the game; each character is made in five steps.', 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 box(x1, x2, y, label, strong=False, h=40):
        out.append(f'<rect x="{x1}" y="{y}" width="{x2-x1}" height="{h}" rx="{12 if strong else 6}" '
                   f'fill="{PALE_ if strong else flowcharts.SURF}" stroke="{BLUE_ if strong else INK2_}" stroke-width="1.4"/>')
        out.extend(L((x1 + x2) / 2, y + h / 2, label, 11.5, 'middle'))

    def line(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.3"{extra} marker-end="url(#ah)"/>')
        if label:
            out.append(T(lx, ly, label, 10.5, INK2_, None, anchor))

    box(22, 112, 80, 'Start menu')
    box(200, 350, 80, 'Party screen:\nfour boxes', True)
    box(520, 680, 80, 'Enter the game: status,\nfood, items, spells')
    box(400, 530, 150, 'View or delete')
    box(20, 140, 220, 'Race and sex')
    box(180, 320, 220, 'Class allowed by the\nrace and the party')
    box(360, 500, 220, 'Alignment allowed by\nthe class and the party')
    box(540, 685, 220, 'Roll attributes, levels\nand hit points')
    box(540, 685, 310, 'Stats screen', True)
    box(360, 500, 310, 'Enter a name')
    line('M112,100 L197,100', 'START A NEW', 155, 114)
    out.append(T(155, 126, 'PARTY', 10.5, INK2_, None, 'middle'))
    line('M350,100 L517,100', 'PLAY, four characters', 434, 90)
    line('M330,120 L420,148', 'filled box', 466, 130, 'start')
    line('M450,150 L355,118')
    line('M210,120 L90,218', 'empty box', 140, 170, 'end')
    for a, b in [(140, 180), (320, 360), (500, 540)]:
        line(f'M{a},233 L{b-3},233')
    for a, b in [(180, 140), (360, 320)]:
        line(f'M{a},250 L{b+3},250', 'back', (a + b) / 2, 266)
    line('M597,260 L597,307')
    line('M627,310 L627,263', 'reroll', 633, 285, 'start')
    out.append(T(612, 364, 'modify a value within its limits,', 10.5, INK2_, None, 'middle'))
    out.append(T(612, 378, 'or choose a portrait: back to it', 10.5, INK2_, None, 'middle'))
    line('M540,330 L503,330', 'keep', 521, 320)
    line('M360,330 L12,330 L12,64 L270,64 L270,77', 'back to the party screen', 186, 320)
    out.append('</svg>')
    (OUT / 'party-creation-screens.svg').write_text('\n'.join(out) + '\n', encoding='utf-8')


creation_screens()
print(f'written to {OUT}')
