"""Draw a 16x16 pixel axe and export PNGs using only Python's standard library."""
from pathlib import Path
import struct
import zlib

# Each character is exactly one pixel. The handle runs from bottom-left to top-right.
SPRITE = [
    '................',
    '........oo......',
    '......oosso.....',
    '.....osllsso....',
    '....oslwwlsso...',
    '...oslwwwlsso...',
    '...oslwwlsssoo..',
    '....osllssbbso..',
    '.....osssobBo...',
    '......ooobBro...',
    '.......obBro....',
    '......obBro.....',
    '.....obBro......',
    '....obBro.......',
    '...obBro........',
    '....ooo.........',
]
PALETTE = {
    '.': (0, 0, 0, 0),
    'o': (35, 39, 47, 255),   # dark outline
    's': (100, 120, 137, 255),
    'l': (177, 199, 208, 255),
    'w': (235, 246, 245, 255),
    'b': (119, 67, 38, 255),
    'B': (193, 126, 65, 255),
    'r': (155, 89, 43, 255),
}
assert len(SPRITE) == 16 and all(len(row) == 16 for row in SPRITE)


def chunk(kind, data):
    return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xFFFFFFFF)


def save_png(path, scale=1):
    size = 16 * scale
    scanlines = bytearray()
    for row in SPRITE:
        pixels = b''.join(bytes(PALETTE[pixel]) * scale for pixel in row)
        for _ in range(scale):
            scanlines.extend(b'\0' + pixels)
    png = b'\x89PNG\r\n\x1a\n'
    png += chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0))
    png += chunk(b'IDAT', zlib.compress(bytes(scanlines), 9))
    png += chunk(b'IEND', b'')
    path.write_bytes(png)


if __name__ == '__main__':
    output = Path(__file__).resolve().parent
    save_png(output / 'axe.png')
    save_png(output / 'axe_preview.png', scale=20)
    print('Exported axe.png (16x16 RGBA) and axe_preview.png (320x320 nearest-neighbor).')
