#!/usr/bin/env python3
"""Cut c02 parts sheet (+ heads) into rig parts. Out: parts/*.png, parts.json, debug-pivots.png"""
import json, os, numpy as np, cv2
from PIL import Image, ImageDraw
HERE = os.path.dirname(os.path.abspath(__file__))
SRC = f'{HERE}/gen/c02-fixed.png'  # c02 + torso hole filled (call 8)
img = np.array(Image.open(SRC).convert('RGB'))
H, W = img.shape[:2]

def fg_mask(rgb):
    white = rgb.min(axis=2) > 225
    n, lab = cv2.connectedComponents(white.astype(np.uint8), connectivity=4)
    border = np.unique(np.concatenate([lab[0], lab[-1], lab[:, 0], lab[:, -1]]))
    bg = np.isin(lab, border) & white
    return cv2.morphologyEx((~bg).astype(np.uint8), cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))

fg = fg_mask(img)
ncomp, lab = cv2.connectedComponents(fg, connectivity=8)
def comp_at(x, y): return lab == lab[y, x]

def circle(c, r):
    m = np.zeros((H, W), np.uint8); cv2.circle(m, (int(c[0]), int(c[1])), int(r), 1, -1); return m.astype(bool)

def halfplane(p, below):
    yy = np.arange(H)[:, None].repeat(W, 1)
    return yy >= p[1] if below else yy <= p[1]

def soft_alpha(mask):
    m = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8))
    return (cv2.GaussianBlur(m.astype(np.float32), (0, 0), 0.8) * 255).clip(0, 255).astype(np.uint8)

# name: (seed point in component, extra mask fn, pivot, named points)
# points are in SHEET coords; stored relative to crop
P = {}
def part(name, seed, pivot, pts=None, clip=None):
    m = comp_at(*seed)
    if clip is not None: m = m & clip
    P[name] = dict(mask=m, pivot=pivot, pts=pts or {})

ELB_O, ELB_F, KNEE = (247, 688), (422, 690), (688, 655)
part('head', (150, 150), (140, 222))
part('torso', (420, 200), (400, 398), dict(neck=(418, 62), shoulder=(338, 148)))
part('pelvis', (700, 200), (700, 118), dict(hip=(690, 205)))
part('upper', (250, 600), (255, 535), dict(elbow=ELB_O), clip=halfplane(ELB_O, False) | circle(ELB_O, 40))
part('fore_open', (250, 800), ELB_O, dict(wrist=(250, 862)), clip=halfplane(ELB_O, True) | circle(ELB_O, 44))
part('fore_fist', (420, 800), ELB_F, dict(wrist=(415, 862)), clip=halfplane(ELB_F, True) | circle(ELB_F, 44))
part('thigh', (680, 450), (665, 398), dict(knee=KNEE), clip=halfplane(KNEE, False) | circle(KNEE, 46))
# v2: the boot SHAFT belongs to the leg (shin piece already ends in a boot cuff), the foot texture is only the foot.
# shin cut 25 px below the ankle, foot cut just above it; shin is drawn over the foot and hides the seam
ANK_S, ANK_B = (656, 935), (858, 882)
part('shin', (680, 800), KNEE, dict(ankle=ANK_S), clip=(halfplane(KNEE, True) | circle(KNEE, 50)) & halfplane((0, ANK_S[1] + 25), False))
part('boot', (880, 900), ANK_B, dict(toe=(990, 968), heel=(838, 972)), clip=halfplane((0, ANK_B[1] - 8), True))

os.makedirs(f'{HERE}/parts', exist_ok=True)
meta = {}
dbg = Image.fromarray(img).convert('RGB'); d = ImageDraw.Draw(dbg)
for name, p in P.items():
    ys, xs = np.nonzero(p['mask'])
    x0, y0, x1, y1 = xs.min() - 2, ys.min() - 2, xs.max() + 3, ys.max() + 3
    a = soft_alpha(p['mask'])
    rgb = img
    if name == 'pelvis':   # v2: round the back-bottom corner (butt curves into the thigh), ink the new edge, short fade on the rest
        rgb = img.copy(); ys, xs = np.nonzero(p['mask']); bx, by = xs.min(), ys.max()
        RC = 110; cx, cy = bx + RC, by - RC
        yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
        dist = np.hypot(xx - cx, yy - cy); corner = (xx < cx) & (yy > cy)
        a = np.where(corner, a * np.clip(RC + 0.5 - dist, 0, 1), a).astype(np.uint8)
        ink = corner & (np.abs(dist - RC + 2.5) < 2.5) & p['mask']
        rgb[ink] = (24, 22, 34)
        r = np.clip((by - yy) / 14, 0, 1); a = np.where(xx >= cx, a * r, a).astype(np.uint8)
    rgba = np.dstack([rgb, a])[y0:y1, x0:x1]
    Image.fromarray(rgba).save(f'{HERE}/parts/{name}.png')
    rel = lambda q: [int(q[0] - x0), int(q[1] - y0)]
    meta[name] = dict(w=int(x1 - x0), h=int(y1 - y0), pivot=rel(p['pivot']), pts={k: rel(v) for k, v in p['pts'].items()})
    d.rectangle([x0, y0, x1, y1], outline=(0, 160, 255))
    for q, c in [(p['pivot'], (255, 0, 0))] + [(v, (0, 200, 0)) for v in p['pts'].values()]:
        d.ellipse([q[0] - 5, q[1] - 5, q[0] + 5, q[1] + 5], outline=c, width=2)
    d.text((x0 + 3, y0 + 3), name, fill=(255, 0, 0))
dbg.save(f'{HERE}/debug-pivots.png')
json.dump(meta, open(f'{HERE}/parts.json', 'w'), indent=1)
print(json.dumps({k: (v['w'], v['h']) for k, v in meta.items()}))

# ---- heads: aligned 2x crops of sheet region (30,15)-(270,295); same pivot for all
HX, HY = 30, 15
heads = {'neutral': f'{HERE}/gen/ref-head3.png'}   # v2: head turned ~20 deg (call 9) + more East Asian (call 14), expressions calls 15-18
for k in ('happy', 'sad', 'think', 'blink'): heads[k] = f'{HERE}/gen/head3-{k}-al.png'
masks = {k: fg_mask(np.array(Image.open(v).convert('RGB'))) for k, v in heads.items()}
# drop specks: keep biggest component
for k, m in masks.items():
    n, l, st, _ = cv2.connectedComponentsWithStats(m, connectivity=8)
    masks[k] = (l == 1 + np.argmax(st[1:, 4])).astype(np.uint8)
union = np.any(np.stack(list(masks.values())), 0)
ys, xs = np.nonzero(union); x0, y0, x1, y1 = xs.min() - 2, ys.min() - 2, xs.max() + 3, ys.max() + 3
for k, v in heads.items():
    rgb = np.array(Image.open(v).convert('RGB'))
    Image.fromarray(np.dstack([rgb, soft_alpha(masks[k])])[y0:y1, x0:x1]).save(f'{HERE}/parts/head_{k}.png')
piv = ((140 - HX) * 2 - x0, (222 - HY) * 2 - y0)
meta['head2x'] = dict(w=int(x1 - x0), h=int(y1 - y0), pivot=[int(piv[0]), int(piv[1])], scale=0.5,
                      pts=dict(chin=[int((222 - HX) * 2 - x0), int((212 - HY) * 2 - y0)]))
json.dump(meta, open(f'{HERE}/parts.json', 'w'), indent=1)
print('heads', meta['head2x'])
