"""Draw a diagonal 16x16 pixel axe and export PNGs using only Python's stdlib."""

from pathlib import Path
import struct
import zlib


SIZE = 16
PALETTE = {
    ".": (0, 0, 0, 0),
    "O": (31, 35, 47, 255),      # Outline
    "S": (75, 94, 113, 255),     # Steel shadow
    "M": (136, 164, 179, 255),   # Steel
    "L": (203, 230, 234, 255),   # Sharpened edge
    "W": (246, 255, 248, 255),   # Glint
    "B": (151, 85, 48, 255),     # Oak handle
    "H": (224, 160, 86, 255),    # Handle highlight
    "D": (105, 59, 42, 255),     # Handle shadow
}

pixels = [["."] * SIZE for _ in range(SIZE)]

# The shaft runs from the lower left toward the upper right.
for y in range(4, 14):
    x = 15 - y
    pixels[y][x - 1:x + 3] = ["O", "H", "B", "O"]
pixels[13][2] = "B"
pixels[13][3] = "D"
pixels[14][2:4] = ["O", "O"]

# Hand-placed pixels form the broad cutting edge, socket, and short poll.
head = [
    (6, 1, "OOO"),
    (4, 2, "OOLLMOO"),
    (3, 3, "OLWMMMSOO"),
    (3, 4, "OLMMMSSSMO"),
    (3, 5, "OLMMSSOBSMO"),
    (4, 6, "OMMSOHBOSMO"),
    (5, 7, "OOOHBOOSMO"),
    (11, 8, "OOOO"),
]
for x, y, row in head:
    pixels[y][x:x + len(row)] = row


def write_png(path: Path, scale: int = 1) -> None:
    """Write lossless RGBA PNG; integer scaling preserves crisp pixel edges."""
    width = height = SIZE * scale
    scanlines = bytearray()
    for row in pixels:
        expanded = b"".join(bytes(PALETTE[color]) * scale for color in row)
        for _ in range(scale):
            scanlines.extend(b"\x00" + expanded)

    def chunk(kind: bytes, data: bytes) -> bytes:
        checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
        return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)

    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(scanlines), 9))
        + chunk(b"IEND", b"")
    )


if __name__ == "__main__":
    folder = Path(__file__).resolve().parent
    write_png(folder / "axe.png")
    write_png(folder / "axe-preview.png", scale=24)
    print("Created axe.png (16x16) and axe-preview.png (384x384).")
