"""Angular silhouette reconstruction for stylized orthographic head turnarounds.
Assumes evenly spaced azimuths, consistent framing, and approximate orthographic cameras.
No learned 3D model or Blender needed.
"""
from pathlib import Path
import sys
import cv2
import numpy as np
from PIL import Image
from scipy.ndimage import gaussian_filter1d
import trimesh

INPUT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name('source-views.webp')
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else Path.cwd() / 'kiku-reconstruction-output'
OUT.mkdir(parents=True, exist_ok=True)
SOURCE = np.asarray(Image.open(INPUT).convert('RGB'))
HEIGHT,WIDTH = SOURCE.shape[:2]
VIEWS = []
MASKS = []
for idx in range(8):
    row, col = divmod(idx, 4)
    tile = SOURCE[round(row*HEIGHT/2):round((row+1)*HEIGHT/2),round(col*WIDTH/4):round((col+1)*WIDTH/4)].copy()
    red,green,blue = [tile[:,:,axis].astype(np.int16) for axis in range(3)]
    skin = ((red > 65)&(red < 245)&(green < 220)&(red - green > 16)&(green - blue > 6)).astype('uint8')*255
    # Close thin line-art cracks and include dark facial details inside silhouette.
    skin = cv2.morphologyEx(skin,cv2.MORPH_CLOSE,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(13,13)))
    contours,_=cv2.findContours(skin,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    best=max(contours,key=cv2.contourArea)
    mask=np.zeros_like(skin); cv2.drawContours(mask,[best],-1,255,-1)
    VIEWS.append(tile);MASKS.append(mask)
    cv2.imwrite(str(OUT/f'mask-{idx:03d}.png'),mask)
    print(idx,tile.shape,'bounds',cv2.boundingRect(best),'area',cv2.contourArea(best))

# Compute per-height intervals, using original orthographic horizontal framing.
# Coordinates are image pixels translated into a shared head-relative frame.
W = min(v.shape[1] for v in VIEWS); H = min(v.shape[0] for v in VIEWS)
# Render 1 world unit as 290 reference pixels; top of head ~ y=18, base y=405.
PIXELS_PER_UNIT=280
ZS = np.linspace((H/2-418)/PIXELS_PER_UNIT,(H/2-16)/PIXELS_PER_UNIT,180)
PHIS = np.linspace(0,2*np.pi,128,endpoint=False)
ANGLES = np.arange(8)*np.pi/4

# Different crops can shift a few pixels; align scalp tip of each view to a common image row,
# and each scalp center to the tile center (the generated layout approximates this already).
# This avoids falsely interpreting the contact-sheet position as 3D translation.
scalp_centers=[]
scalp_tops=[]
for m in MASKS:
    ys,xs=np.where(m>0); top=int(ys.min())
    band=xs[ys<top+70]
    scalp_centers.append(float(np.median(band)))
    scalp_tops.append(top)
print('scalp centers',scalp_centers,'tops',scalp_tops)
# Crop origins aligned via approximate scalp center across views.
# Note scalp center of back/right view can be shifted by artistic perspective.
centers_x=np.asarray(scalp_centers)
median_top = float(np.median(scalp_tops))
intervals=np.zeros((len(ZS),8,2),dtype=float)
for zidx,z in enumerate(ZS):
    pixel_y = int(round(H/2-z*PIXELS_PER_UNIT))
    for i,mask in enumerate(MASKS):
        local_y = np.clip(int(round(pixel_y + scalp_tops[i]-median_top)),0,mask.shape[0]-1)
        pixels=np.flatnonzero(mask[local_y]>0)
        if len(pixels)<2:
            intervals[zidx,i] = np.nan
        else:
            intervals[zidx,i] = ((pixels.min()-centers_x[i])/PIXELS_PER_UNIT,
                                  (pixels.max()-centers_x[i])/PIXELS_PER_UNIT)
# A head turned away should still share centerline. Use geometric constraints as is.
for i in range(8):
    for side in range(2):
        vector=intervals[:,i,side]
        valid=np.flatnonzero(np.isfinite(vector))
        if not len(valid): raise ValueError('Missing silhouette')
        intervals[:,i,side]=np.interp(np.arange(len(ZS)),valid,vector[valid])
# Smooth 1D band variation to avoid pixel staircase and per-view local irregularities.
intervals=gaussian_filter1d(intervals,sigma=1.4,axis=0)

# Compute the radial function of the strip-intersection polygon at each z.
# The origin of the cross section is solved by least squares from its 8 projected band midpoints.
projections=np.stack([np.cos(ANGLES),-np.sin(ANGLES)],axis=1)
radials=np.zeros((len(ZS),len(PHIS)))
centers=np.zeros((len(ZS),2))
for j,band in enumerate(intervals):
    mids=band.mean(axis=1)
    center=np.linalg.lstsq(projections,mids,rcond=None)[0]
    centers[j]=center
    upper=band[:,1]-projections@center
    lower=-band[:,0]+projections@center
    constraints=np.vstack([projections,-projections])
    bounds=np.concatenate([upper,lower]); bounds=np.maximum(bounds,0.003)
    radial_denominators=constraints@np.stack([np.cos(PHIS),np.sin(PHIS)],axis=0)
    rs=np.where(radial_denominators>1e-5,bounds[:,None]/np.maximum(radial_denominators,1e-5),np.inf)
    radials[j]=np.min(rs,axis=0)
# Smooth across θ and z; circular boundary conditions are important.
radials=gaussian_filter1d(radials,1.3,axis=1,mode='wrap')
radials=gaussian_filter1d(radials,1.3,axis=0,mode='nearest')
centers=gaussian_filter1d(centers,1.5,axis=0)
# Closing the uppermost scalp at a slightly higher apex avoids a flat cap.
radials[-1] *= 0.45
radials[-2] *= 0.86
# Ring mesh, with two planar end caps to make it watertight.
vertices=[]
for j,z in enumerate(ZS):
    for k,phi in enumerate(PHIS):
        x=centers[j,0]+radials[j,k]*np.cos(phi)
        y=centers[j,1]+radials[j,k]*np.sin(phi)
        vertices.append([x,y,z])
vertices.extend([[*centers[0],ZS[0]],[*centers[-1],ZS[-1]+0.017]])
vertices=np.array(vertices)
faces=[]; ns=len(PHIS)
for j in range(len(ZS)-1):
    for k in range(ns):
        l=(k+1)%ns
        a=j*ns+k; b=j*ns+l; c=(j+1)*ns+k; d=(j+1)*ns+l
        faces.extend([[a,b,c],[b,d,c]])
for k in range(ns):
    l=(k+1)%ns
    faces.append([len(vertices)-2,l,k])
    a=(len(ZS)-1)*ns
    faces.append([len(vertices)-1,a+k,a+l])
mesh=trimesh.Trimesh(vertices=vertices,faces=np.array(faces),process=True)
mesh.fix_normals()
mesh.export(OUT/'kiku-bald-visual-hull.glb')
mesh.export(OUT/'kiku-bald-visual-hull.obj')
print('mesh',len(mesh.vertices),len(mesh.faces),'bounds',mesh.bounds.tolist(),'watertight',mesh.is_watertight,'volume',mesh.volume)

# Project mesh rings and measure silhouette overlap against generated masks,
# using the same view-center and top alignment that defined the model.
metrics=[]
for idx,angle in enumerate(ANGLES):
    v=mesh.vertices
    projected=(v[:,0]*np.cos(angle)-v[:,1]*np.sin(angle))*PIXELS_PER_UNIT+centers_x[idx]
    py=(H/2-v[:,2]*PIXELS_PER_UNIT) + scalp_tops[idx]-median_top
    projected_pts=np.stack([projected,py],axis=1).round().astype(np.int32)
    projected_mask=np.zeros_like(MASKS[idx])
    for a,b,c in mesh.faces:
        cv2.fillConvexPoly(projected_mask,projected_pts[[a,b,c]],255)
    target=MASKS[idx]>0; observed=projected_mask>0
    intersection=np.count_nonzero(target&observed); union=np.count_nonzero(target|observed)
    iou=intersection/max(1,union)
    miss=np.count_nonzero(target&~observed)/max(1,np.count_nonzero(target))
    excess=np.count_nonzero(observed&~target)/max(1,np.count_nonzero(target))
    metrics.append({'angle_deg':int(np.rad2deg(angle).round()),'iou':round(iou,5),'miss_fraction':round(miss,5),'excess_fraction':round(excess,5)})
    image=VIEWS[idx].copy()
    # cyan model contour, orange target contour
    contours,_=cv2.findContours(projected_mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    if contours:cv2.drawContours(image,contours,-1,(60,190,240),2)
    cv2.imwrite(str(OUT/f'overlay-{idx:03d}.png'),cv2.cvtColor(image,cv2.COLOR_RGB2BGR))
print('metrics',metrics,'mean iou',np.mean([m['iou'] for m in metrics]))
np.savez_compressed(OUT/'silhouette-constraints.npz', intervals=intervals, z=ZS, azimuth=ANGLES, radius=radials, centers=centers,scalp_centers=centers_x,scalp_tops=scalp_tops)
import json
(OUT/'metrics.json').write_text(json.dumps({'views':metrics,'mean_iou':float(np.mean([m['iou'] for m in metrics])),'vertices':len(mesh.vertices),'triangles':len(mesh.faces),'watertight':bool(mesh.is_watertight),'input':str(INPUT)},indent=2))
