#!/usr/bin/env python3
"""Generate the figures of the saving and restoring pages.

The figures are original schematic drawings that transcribe the rules written
on the pages; the program reads no file.

Usage:
    python3 scripts/saves/make_save_figures.py [output_directory]

The default is docs/saves/img/.
"""
import sys
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
from svgkit import frame, write, text, INK, INK2, GRID, BLUE, LIGHT, PALE, SHADE  # noqa: E402

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

flowcharts.chain(
    OUT / 'saves-level-change.svg', 'What a level change stores and restores',
    'The record of the old level is written before the new level is read.',
    "The steps of a level change. The game settles the level, writes its record to LEVELS.TMP and sets its "
    "bit, then reads the new level's INF data. If the new level has a record, its walls, monsters and "
    'temporary walls come from the record; otherwise the walls come from the map and the monsters from the '
    'INF file. In both cases the item lists of the blocks are rebuilt from the item table.',
    [('step', 'Settle the level'),
     ('step', 'Write its record to LEVELS.TMP\nand set its bit'),
     ('step', "Read the new level's INF data"),
     ('ask', 'Has the new level a record?', 'yes', 'Walls, monsters and temporary\nwalls from the record', 'no'),
     ('step', 'Walls from the map, monsters\nfrom the INF file'),
     ('step', 'In both cases: rebuild the block item\nlists from the item table')])


# The seven parts of a saved game, docs/saves/README.md.
PARTS = [('Description', 20), ('Six characters', 6 * 345), ('Party and world', 92), ('Items', 600 * 14),
         ('Level records', 17 * 2130), ('Options', 3), ('Conjured-weapon types', 6 * 16)]
total = sum(n for _, n in PARTS)
assert total == 46891, total
W, H = 700, 270
out = frame(W, H, 'What a saved game holds',
            'The seven parts of a saved game, one after the other, in bytes: description 20; six characters 2,070; '
            'party and world variables 92; items 8,400; level records 36,210; options 3; conjured-weapon item types '
            f'96; {total:,} bytes in all. The level records take more than three quarters of the file.',
            f'Seven parts, one after the other, {total:,} bytes; widths in proportion to the sizes.')
x, y, w = 20, 76, 660
fills = ['#d8d6d0', '#a9c9f0', '#8a8984', '#5596e0', '#2a78d6', '#eb6834', '#2f8f5b']
for (name, n), fill in zip(PARTS, fills):
    width = max(w * n / total, 3)
    out.append(f'<rect x="{x:.1f}" y="{y}" width="{width:.1f}" height="30" fill="{fill}" stroke="#ffffff"/>')
    x += width
for k, ((name, n), fill) in enumerate(zip(PARTS, fills)):
    lx, ly = 20 + (k // 4) * 340, 134 + (k % 4) * 20
    out.append(f'<rect x="{lx}" y="{ly - 7}" width="14" height="14" rx="2" fill="{fill}"/>')
    out.append(text(lx + 22, ly, f'{k + 1}. {name}: {n:,} bytes', 11.5, INK))
out.append(text(20, H - 40, 'One level record per dungeon level, 2,130 bytes each; only the levels marked in the party', 11, INK2))
out.append(text(20, H - 22, 'variables are used. FINAL.SAV has the same layout.', 11, INK2))
write(OUT, 'saves-file-layout.svg', out)

flowcharts.chain(
    OUT / 'saves-loading.svg', 'Loading a saved game',
    'The file is checked only for the size of its parts.',
    'How a saved game is loaded. The whole file is read; if any of the seven parts is short, nothing is restored '
    'and the load fails. Otherwise the level in progress is settled; the characters are restored and their timers '
    'turned back into deadlines; the party and world variables, the items, the level records, the options and the '
    'conjured-weapon types are restored; the portraits are drawn again; the saved level is loaded from its record; '
    'and the held item is given back. From the start menu, the loader stops after the portraits.',
    [('ask', 'Has each of the seven parts\nits expected size?', 'no', 'Refused: the file may be\ncorrupt; nothing changes', 'yes'),
     ('step', 'Settle the level in progress'),
     ('step', 'Characters restored; timers turned\nback into deadlines'),
     ('step', 'Party, items, level records over\nLEVELS.TMP, options, item types'),
     ('step', 'Portraits drawn again'),
     ('step', 'The saved level loaded from its record'),
     ('step', 'The held item given back')],
    'From the start menu, the loader stops after the portraits; the start of the game loads the level.')
