#!/usr/bin/env python3
"""Itemsmith cutter: turn a raw Itemsmith sheet into game-ready files.

  python3 itemsmith_cut.py <sheet.png | https://game-assets.realisticragdollengine.com/api/sheet/....png> \
      --key green --kind items --style pixel --grid 32 --out assets/potions

Writes one transparent PNG per asset, <name>-sheet.png and <name>-sheet.json (TexturePacker JSON Hash, read by
Phaser, PixiJS, Godot and Unity importers; pivot at the feet, nine-slice borders for UI pieces).
Same steps as the website (https://game-assets.realisticragdollengine.com/): key out the flat background, split the
sheet into separate objects, make tiles seamless, snap pixel art to a real grid with a 16-color palette.
Needs Python 3.8+, Pillow and numpy (pip install pillow numpy). scipy is used if installed (faster), not required.
MIT license.
"""
import argparse, io, json, os, re, sys, urllib.request
from collections import deque

try:
    import numpy as np
    from PIL import Image
except ImportError:
    sys.exit('Needs Pillow and numpy: pip install pillow numpy')
try:
    from scipy import ndimage
except ImportError:
    ndimage = None


def label(mask, eight=False):
    """Connected components of a boolean array -> (labels, count)."""
    if ndimage is not None:
        st = np.ones((3, 3), bool) if eight else None
        return ndimage.label(mask, structure=st)
    h, w = mask.shape
    lab = np.zeros((h, w), np.int32)
    n = 0
    nb = [(-1, 0), (1, 0), (0, -1), (0, 1)] + ([(-1, -1), (-1, 1), (1, -1), (1, 1)] if eight else [])
    for y0, x0 in zip(*np.nonzero(mask)):
        if lab[y0, x0]:
            continue
        n += 1
        lab[y0, x0] = n
        q = deque([(y0, x0)])
        while q:
            y, x = q.popleft()
            for dy, dx in nb:
                yy, xx = y + dy, x + dx
                if 0 <= yy < h and 0 <= xx < w and mask[yy, xx] and not lab[yy, xx]:
                    lab[yy, xx] = n
                    q.append((yy, xx))
    return lab, n


def key_out(rgb, key):
    """Flat green/magenta background -> alpha. Only key regions touching the border, or enclosed regions that are
    almost pure key color (the gap inside a bow), become transparent; a green potion's liquid stays."""
    r, g, b = (rgb[..., i].astype(np.float32) for i in range(3))
    sat = (np.minimum(r, b) - g) if key == 'magenta' else (g - np.maximum(r, b))
    lab, n = label(sat > 40)
    bg = np.zeros(n + 1, bool)
    if n:
        sums = np.bincount(lab.ravel(), weights=sat.ravel(), minlength=n + 1)
        cnts = np.bincount(lab.ravel(), minlength=n + 1)
        bg[1:] = sums[1:] / np.maximum(cnts[1:], 1) > 150
        for edge in (lab[0], lab[-1], lab[:, 0], lab[:, -1]):
            bg[np.unique(edge)] = True
        bg[0] = False
    isbg = bg[lab]
    alpha = np.where(isbg, np.clip(1 - (sat - 40) / 60, 0, 1), 1.0)
    soft = alpha < 1
    if key == 'magenta':
        m = np.clip(np.minimum(r, b) - (g + 10), 0, None)
        r = np.where(soft, r - m, r); b = np.where(soft, b - m, b)
    else:
        g = np.where(soft, np.minimum(g, np.maximum(r, b) + 10), g)
    return np.dstack([r, g, b, alpha * 255]).clip(0, 255).astype(np.uint8)


def split(rgba, min_share=0.012, glue=True):
    """Separate objects on an 8 px cell grid (cells within one cell of each other are glued unless glue=False)."""
    H, W = rgba.shape[:2]
    C = 8
    gh, gw = -(-H // C), -(-W // C)
    op = np.zeros((gh * C, gw * C), bool)
    op[:H, :W] = rgba[..., 3] > 128
    cells = op.reshape(gh, C, gw, C).sum(axis=(1, 3)) >= 4
    dil = cells.copy()
    if glue:
        p = np.pad(cells, 1)
        dil = np.zeros_like(cells)
        for dy in range(3):
            for dx in range(3):
                dil |= p[dy:dy + gh, dx:dx + gw]
    lab, n = label(dil, eight=True)
    sizes = np.bincount(lab[cells], minlength=n + 1)
    total = sizes.sum()
    boxes = []
    for i in range(1, n + 1):
        if sizes[i] < max(6, total * min_share):
            continue
        ys, xs = np.nonzero((lab == i) & cells)
        y0, y1, x0, x1 = ys.min() * C, min(H, (ys.max() + 1) * C), xs.min() * C, min(W, (xs.max() + 1) * C)
        a = rgba[y0:y1, x0:x1, 3] > 24
        if not a.any():
            continue
        yy, xx = np.nonzero(a)
        boxes.append((x0 + xx.min(), y0 + yy.min(), xx.max() - xx.min() + 1, yy.max() - yy.min() + 1))
    boxes = [b for b in boxes if b[2] > 4 and b[3] > 4]
    if not boxes:
        return []
    row_h = max(b[3] for b in boxes) / 2
    boxes.sort(key=lambda b: (round((b[1] + b[3] / 2) / row_h), b[0]))
    return [rgba[y:y + h, x:x + w].copy() for x, y, w, h in boxes]


def seamless(rgba):
    """Square tile that wraps: blend with a half-shifted copy of itself, weighted to the copy near the borders."""
    h, w = rgba.shape[:2]
    t = round(min(w, h) * 0.03)
    a = rgba[t:h - t, t:w - t]
    n = min(a.shape[:2])
    y0, x0 = (a.shape[0] - n) // 2, (a.shape[1] - n) // 2
    a = a[y0:y0 + n, x0:x0 + n, :3].astype(np.float32)
    shifted = np.roll(np.roll(a, n // 2, axis=0), n // 2, axis=1)
    idx = np.arange(n)
    e = np.minimum.outer(np.minimum(idx, n - 1 - idx), np.minimum(idx, n - 1 - idx))
    wgt = np.clip(e / (n / 4), 0, 1)[..., None]
    out = a * wgt + shifted * (1 - wgt)
    return np.dstack([out, np.full((n, n), 255, np.float32)]).astype(np.uint8)


def pixelate(rgba, n, colors=16):
    """Longest side -> n pixels; alpha by majority, color = mean of opaque pixels; then a small palette."""
    h, w = rgba.shape[:2]
    sc = max(w, h) / n
    ow, oh = max(1, round(w / sc)), max(1, round(h / sc))
    out = np.zeros((oh, ow, 4), np.uint8)
    xs = [int(i * w / ow) for i in range(ow + 1)]
    ys = [int(i * h / oh) for i in range(oh + 1)]
    for oy in range(oh):
        for ox in range(ow):
            blk = rgba[ys[oy]:max(ys[oy] + 1, ys[oy + 1]), xs[ox]:max(xs[ox] + 1, xs[ox + 1])].reshape(-1, 4)
            opq = blk[blk[:, 3] > 128]
            if len(opq) * 2 >= len(blk) and len(opq):
                out[oy, ox, :3] = opq[:, :3].mean(axis=0)
                out[oy, ox, 3] = 255
    if colors:
        mask = out[..., 3] > 0
        if mask.sum() > colors:
            q = Image.fromarray(out[..., :3]).quantize(colors=colors, method=Image.Quantize.MEDIANCUT).convert('RGB')
            out[..., :3] = np.where(mask[..., None], np.asarray(q), 0)
    return out


def align(frames):
    cw, ch = max(f.shape[1] for f in frames), max(f.shape[0] for f in frames)
    res = []
    for f in frames:
        c = np.zeros((ch, cw, 4), np.uint8)
        x = (cw - f.shape[1]) // 2
        c[ch - f.shape[0]:, x:x + f.shape[1]] = f
        res.append(c)
    return res


def main():
    ap = argparse.ArgumentParser(description='Cut a raw Itemsmith sheet into transparent PNGs + sprite sheet + JSON atlas.')
    ap.add_argument('src', help='sheet PNG path or https URL')
    ap.add_argument('--key', choices=['green', 'magenta'], default='green')
    ap.add_argument('--kind', choices=['items', 'icons', 'characters', 'tiles', 'ui'], default='items')
    ap.add_argument('--style', choices=['pixel', 'cartoon', 'painted', 'flat'], default='pixel')
    ap.add_argument('--grid', default=None, help='16|24|32|48|64 or off (default: 32 for pixel style, off otherwise)')
    ap.add_argument('--out', default='assets/itemsmith')
    a = ap.parse_args()
    grid = a.grid or ('32' if a.style == 'pixel' else 'off')
    if a.src.startswith('http'):
        req = urllib.request.Request(a.src, headers={'User-Agent': 'itemsmith-cut/1.0'})
        data = urllib.request.urlopen(req, timeout=60).read()
        img = Image.open(io.BytesIO(data))
    else:
        img = Image.open(a.src)
    rgba = key_out(np.asarray(img.convert('RGB')), a.key)
    parts = split(rgba, glue=a.kind not in ('ui', 'tiles'))
    if a.kind == 'tiles':
        parts = [seamless(p) for p in parts if p.shape[0] > 60 and p.shape[1] > 60]
    if grid != 'off':
        n = int(grid)
        parts = [pixelate(p, int(n * 1.5) if a.kind == 'characters' else n) for p in parts]
    if not parts:
        sys.exit('Nothing could be cut out of this sheet.')
    os.makedirs(a.out, exist_ok=True)
    base = re.sub(r'[^a-z0-9]+', '-', os.path.basename(os.path.normpath(a.out)).lower()).strip('-') or 'assets'
    names = [f'{base}-{i + 1}' for i in range(len(parts))]
    for nm, p in zip(names, parts):
        Image.fromarray(p).save(os.path.join(a.out, nm + '.png'))
    cw, ch, pad = max(p.shape[1] for p in parts), max(p.shape[0] for p in parts), 2
    cols = int(np.ceil(np.sqrt(len(parts)))); rows = int(np.ceil(len(parts) / cols))
    sheet = np.zeros((rows * (ch + pad), cols * (cw + pad), 4), np.uint8)
    frames = {}
    for i, (nm, p) in enumerate(zip(names, parts)):
        x, y = (i % cols) * (cw + pad), (i // cols) * (ch + pad)
        sheet[y:y + p.shape[0], x:x + p.shape[1]] = p
        h, w = p.shape[:2]
        fr = {'frame': {'x': x, 'y': y, 'w': w, 'h': h}, 'rotated': False, 'trimmed': False,
              'spriteSourceSize': {'x': 0, 'y': 0, 'w': w, 'h': h}, 'sourceSize': {'w': w, 'h': h}, 'pivot': {'x': 0.5, 'y': 1}}
        if a.kind == 'ui':
            s = max(2, round(min(w, h) * 0.25)); fr['slice'] = {'left': s, 'top': s, 'right': s, 'bottom': s}
        frames[nm] = fr
    Image.fromarray(sheet).save(os.path.join(a.out, base + '-sheet.png'))
    meta = {'app': 'https://game-assets.realisticragdollengine.com/', 'image': base + '-sheet.png', 'format': 'RGBA8888',
            'size': {'w': sheet.shape[1], 'h': sheet.shape[0]}, 'scale': '1'}
    json.dump({'frames': frames, 'meta': meta}, open(os.path.join(a.out, base + '-sheet.json'), 'w'), indent=1)
    print(f'{len(parts)} {a.kind} -> {a.out}/ ({", ".join(f"{p.shape[1]}x{p.shape[0]}" for p in parts[:8])}{" ..." if len(parts) > 8 else ""})')
    print(f'sheet: {a.out}/{base}-sheet.png + {base}-sheet.json')


if __name__ == '__main__':
    main()
