#!/usr/bin/env python3
"""
Slice an AI-generated sprite sheet into individual transparent PNGs.

Works on any sheet with a roughly solid background color (what Gemini/Nano Banana
produce): samples the background from the corners, keys it out, finds each sprite
as a connected region, and saves every one as a cropped PNG with a real alpha
channel — ready for Unity, Godot, web, anywhere.

Requires:  pip install opencv-python numpy pillow

Usage:
  python slice_sheet.py --sheet "Halloween Sprite Sheet.png" --out cutouts
  python slice_sheet.py --sheet sheet.png --out cutouts --thresh 42 --min-area 600
"""
import argparse
import os

import cv2
import numpy as np


def main():
    ap = argparse.ArgumentParser(description="Cut a sprite sheet into transparent PNGs")
    ap.add_argument("--sheet", required=True, help="sprite sheet image (solid-ish background)")
    ap.add_argument("--out", default="cutouts", help="output folder")
    ap.add_argument("--thresh", type=float, default=40, help="background color distance threshold")
    ap.add_argument("--min-area", type=int, default=500, help="ignore blobs smaller than this (px)")
    ap.add_argument("--pad", type=int, default=6, help="padding around each sprite crop")
    a = ap.parse_args()

    img = cv2.imread(a.sheet, cv2.IMREAD_COLOR)
    if img is None:
        raise SystemExit(f"could not read {a.sheet}")
    H, W = img.shape[:2]

    # background = median of the four corner patches
    c = 12
    corners = np.concatenate([img[:c, :c].reshape(-1, 3), img[:c, -c:].reshape(-1, 3),
                              img[-c:, :c].reshape(-1, 3), img[-c:, -c:].reshape(-1, 3)])
    bg = np.median(corners, axis=0)

    dist = np.linalg.norm(img.astype(np.float32) - bg, axis=2)
    bg_like = (dist <= a.thresh).astype(np.uint8)
    # Background = only the bg-colored region CONNECTED TO THE IMAGE BORDER.
    # White areas sealed inside a sprite's outline (a ghost's body, a skull, candle wax)
    # are not reachable from the border, so they stay part of the sprite.
    nbg, bglabels = cv2.connectedComponents(bg_like, connectivity=4)
    border_ids = set(np.unique(np.concatenate([
        bglabels[0, :], bglabels[-1, :], bglabels[:, 0], bglabels[:, -1]])))
    border_ids.discard(0)
    true_bg = np.isin(bglabels, list(border_ids)) if border_ids else np.zeros_like(bg_like, bool)
    fg = (~true_bg).astype(np.uint8)
    fg = cv2.morphologyEx(fg, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
    fg = cv2.morphologyEx(fg, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))

    n, labels, stats, _ = cv2.connectedComponentsWithStats(fg, connectivity=8)
    boxes = [(x, y, w, h, i) for i in range(1, n)
             for x, y, w, h, area in [stats[i][:5]] if area >= a.min_area]
    # row-major order: bucket by row bands, then left-to-right
    boxes.sort(key=lambda b: (round((b[1] + b[3] / 2) / (H / 12)), b[0]))

    os.makedirs(a.out, exist_ok=True)
    for idx, (x, y, w, h, i) in enumerate(boxes, 1):
        x0, y0 = max(0, x - a.pad), max(0, y - a.pad)
        x1, y1 = min(W, x + w + a.pad), min(H, y + h + a.pad)
        crop = img[y0:y1, x0:x1]
        mask_c = (labels[y0:y1, x0:x1] == i).astype(np.float32)
        # full alpha inside the sprite (interior whites included), feathered 1px at the edge
        alpha = (cv2.GaussianBlur(mask_c, (3, 3), 0) * 255).astype(np.uint8)
        rgba = np.dstack([crop, alpha])
        path = os.path.join(a.out, f"sprite_{idx:02d}.png")
        cv2.imwrite(path, rgba)
    print(f"SAVED {len(boxes)} sprites -> {a.out}/")


if __name__ == "__main__":
    main()
