#!/usr/bin/env python3

from pathlib import Path
from PIL import Image
from PIL import ImageOps

TILE_W = 8
TILE_H = 8

def _tile_box(tile_x: int, tile_y: int) -> tuple[int, int, int, int]:
    left = tile_x * TILE_W
    top = tile_y * TILE_H
    return (left, top, left + TILE_W, top + TILE_H)


def _swap_tiles(img: Image.Image, a: tuple[int, int], b: tuple[int, int]) -> None:
    box_a = _tile_box(*a)
    box_b = _tile_box(*b)

    tile_a = img.crop(box_a).copy()
    tile_b = img.crop(box_b).copy()
    img.paste(tile_a, box_b)
    img.paste(tile_b, box_a)

def _copy_and_mirror_tile(img: Image.Image, a: tuple[int, int], b: tuple[int, int]) -> None:
    base_tile = img.crop(_tile_box(*a)).copy()
    mirrored = ImageOps.mirror(base_tile)
    img.paste(mirrored, _tile_box(*b))


def main() -> int:
    input_file = "GoombaSprites.png"
    output_file =  "GoombaSprites_swapped.png"

    input_path = Path(input_file)
    output_path = Path(output_file)

    img = Image.open(input_path)
    img.load()

    _swap_tiles(img, (0, 1), (1, 0))
    _swap_tiles(img, (0, 2), (1, 1))

    _copy_and_mirror_tile(img, (0, 0), (0, 2))
    _copy_and_mirror_tile(img, (1, 0), (1, 2))

    _copy_and_mirror_tile(img, (0, 1), (0, 3))
    _copy_and_mirror_tile(img, (1, 1), (1, 3))

    img.save(output_path)
    print(f"Wrote {output_path}")
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
