"""Draw a decision chain as an SVG figure: shared by the figure scripts.

A chain is a column of boxes read from top to bottom. A row is either a step,
('step', text), or a question, ('ask', text, side_label, side_outcome,
down_label): the side branch leaves to the right toward its outcome, and the
down label names the branch that goes on. Text uses '\\n' for line breaks.
The drawing is 700 px wide, like every figure of the site, and reads no file.
"""
from html import escape
from pathlib import Path

FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif"
SURF, BORDER, INK, INK2, SHADE, BLUE, PALE = '#fcfcfb', '#dddcd7', '#0b0b0b', '#52514e', '#f1f0ec', '#2a78d6', '#e9f1fb'


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 lines(x, y, s, size, anchor, fill=INK):
    parts = s.split('\n')
    return [text(x, y + (k - (len(parts) - 1) / 2) * (size + 3), p, size, fill, None, anchor)
            for k, p in enumerate(parts)]


def chain(path, title, subtitle, desc, rows, note=None):
    W = 700
    bw, gap, x, y = 360, 26, 20, 74
    heights = [max(42, 18 + 15 * max(len(r[1].split('\n')), len(r[3].split('\n')) if r[0] == 'ask' else 1))
               for r in rows]
    H = y + sum(heights) + gap * (len(rows) - 1) + (44 if note else 20)
    out = [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>']
    for i, r in enumerate(rows):
        bh = heights[i]
        ask = r[0] == 'ask'
        out.append(f'<rect x="{x}" y="{y}" width="{bw}" height="{bh}" rx="{14 if ask else 6}" '
                   f'fill="{PALE if ask else SURF}" stroke="{BLUE if ask else INK2}" stroke-width="1.4"/>')
        out += lines(x + bw / 2, y + bh / 2, r[1], 12, 'middle')
        if ask:
            _, _, side, outcome, down = r
            sx = x + bw + 90
            out.append(f'<line x1="{x+bw}" y1="{y+bh/2}" x2="{sx-2}" y2="{y+bh/2}" stroke="{INK2}" '
                       f'stroke-width="1.4" marker-end="url(#ah)"/>')
            out.append(text(x + bw + 45, y + bh / 2 - 9, side, 11, INK2, None, 'middle'))
            out.append(f'<rect x="{sx}" y="{y}" width="{W-20-sx}" height="{bh}" rx="6" fill="{SHADE}" stroke="{BORDER}"/>')
            out += lines(sx + 10, y + bh / 2, outcome, 11.5, 'start')
        if i < len(rows) - 1:
            out.append(f'<line x1="{x+bw/2}" y1="{y+bh}" x2="{x+bw/2}" y2="{y+bh+gap-2}" stroke="{INK2}" '
                       f'stroke-width="1.4" marker-end="url(#ah)"/>')
            if ask and r[4]:
                out.append(text(x + bw / 2 + 8, y + bh + gap / 2, r[4], 11, INK2))
        y += bh + gap
    if note:
        out.append(text(20, H - 22, note, 11, INK2))
    out.append('</svg>')
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text('\n'.join(out) + '\n', encoding='utf-8')
    print(path)
