"""Draw a diagonal 16x16 pixel axe and export lossless RGBA PNGs.

Run: python3 draw_axe.py
Uses only the Python standard library. Each character is exactly one pixel.
"""
from pathlib import Path
import struct
import zlib

PALETTE = {
    '.': (0, 0, 0, 0),         # Transparent background
    '#': (30, 35, 43, 255),    # Dark outline
    'w': (236, 247, 250, 255), # Blade edge
    's': (172, 194, 205, 255), # Steel
    'd': (99, 123, 142, 255),  # Steel shadow
    'b': (149, 87, 43, 255),   # Wooden handle
    'h': (218, 156, 78, 255),  # Handle highlight
}

PIXELS = [
    '................',
    '........###.....',
    '.......#wws#....',
    '......#wwssd#...',
    '.....#wwssdd##..',
    '.....#wssddbs#..',
    '......#sddbs#...',
    '.......##hb#....',
    '.......#hb#.....',
    '......#hb#......',
    '.....#hb#.......',
    '....#hb#........',
    '...#hb#.........',
    '..#hb#..........',
    '..#b#...........',
    '...#............',
]


def write_png(path, scale=1):
    assert len(PIXELS) == 16 and all(len(row) == 16 for row in PIXELS)
    width = height = 16 * scale
    raw = bytearray()
    for row in PIXELS:
        scanline = b''.join(bytes(PALETTE[pixel]) * scale for pixel in row)
        for _ in range(scale):
            raw.extend(b'\x00' + scanline)

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

    path.write_bytes(
        b'\x89PNG\r\n\x1a\n'
        + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 6, 0, 0, 0))
        + chunk(b'IDAT', zlib.compress(bytes(raw)))
        + chunk(b'IEND', b'')
    )


if __name__ == '__main__':
    destination = Path(__file__).resolve().parent
    write_png(destination / 'axe.png')
    write_png(destination / 'axe-preview.png', scale=20)
    print('Exported axe.png (16x16) and axe-preview.png (320x320).')
