#!/usr/bin/env python3
"""Kiku 2-view, map-guided reconstruction.

Inputs are front/back orthographic source images plus a generated 2x4 image sheet.
Outputs: aligned maps, view-space normal corrections, UV/PBR GLB, validation.
Depth from two opposite views is an *assumed geometric prior*, not measured depth.
"""
from __future__ import annotations

import json
import math
from pathlib import Path

import cv2
import numpy as np
from PIL import Image
from scipy.ndimage import gaussian_filter, map_coordinates
from skimage.measure import marching_cubes
import trimesh
from trimesh.visual.material import PBRMaterial
from trimesh.visual.texture import TextureVisuals

BASE = Path(__file__).resolve().parent
FRONT = BASE / 'reference_front.webp'
BACK = BASE / 'reference_back.webp'
GENERATED = BASE / 'generated_sheet.webp'
RAW = BASE / 'generator'
FINAL = BASE / 'maps'
RAW.mkdir(exist_ok=True)
FINAL.mkdir(exist_ok=True)
COLORS = np.array([
    [0, 0, 0],      # background
    [255, 0, 0],    # skin
    [0, 255, 0],    # undershirt
    [0, 0, 255],    # trousers
    [255, 255, 0],  # harness / equipment
    [255, 0, 255],  # hair
    [0, 255, 255],  # boots
], np.uint8)
ROUGHNESS = np.array([1.0, .60, .88, .91, .69, .70, .62], np.float32)
MATERIAL_NAMES = ['background','skin','tank','trousers','gear','hair','boots']


def save_png(path, data):
    Image.fromarray(np.asarray(np.clip(data, 0, 255), np.uint8)).save(path, optimize=True)


def source_mask(rgb):
    # Background is near-white. The largest object is the connected silhouette.
    difference = np.max(255 - rgb.astype(np.int16), axis=2)
    m = (difference > 25).astype(np.uint8)
    connected, labels, sizes, _ = cv2.connectedComponentsWithStats(m, 8)
    m = (labels == 1 + np.argmax(sizes[1:,4])).astype(np.uint8)
    m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((3,3), np.uint8))
    return m.astype(bool)


def binary_bounds(mask):
    y, x = np.nonzero(mask)
    return [int(x.min()), int(y.min()), int(x.max()+1), int(y.max()+1)]


def intersection_union(a,b):
    return float(np.count_nonzero(a&b))/max(1, int(np.count_nonzero(a|b)))


def register_back(front, back):
    # Register small silhouette mismatch only; ECC at quarter resolution.
    height,width=front.shape
    quarter=(width//4,height//4)
    reference=cv2.resize(front.astype(np.float32),quarter,interpolation=cv2.INTER_AREA)
    moving=cv2.resize(np.fliplr(back).astype(np.float32),quarter,interpolation=cv2.INTER_AREA)
    reference=cv2.GaussianBlur(reference,(5,5),1.3)
    moving=cv2.GaussianBlur(moving,(5,5),1.3)
    warp=np.eye(2,3,dtype=np.float32)
    try:
        cc,warp=cv2.findTransformECC(reference,moving,warp,cv2.MOTION_EUCLIDEAN,(cv2.TERM_CRITERIA_EPS|cv2.TERM_CRITERIA_COUNT,45,1e-5))
        warped=cv2.warpAffine(moving,warp,quarter,flags=cv2.INTER_LINEAR|cv2.WARP_INVERSE_MAP)
        corrected=cv2.resize(warped,(width,height),interpolation=cv2.INTER_LINEAR)>.5
    except cv2.error:
        cc=None
        corrected=np.fliplr(back)
    warp[:,2]*=4.0
    return corrected,warp,cc

def segment_material(rgb, mask):
    height, width = mask.shape
    yy, xx = np.indices(mask.shape)
    image = rgb.astype(np.int16)
    red, green, blue = image.transpose(2,0,1)
    maximum = np.max(rgb,axis=2).astype(np.int16)
    minimum = np.min(rgb,axis=2).astype(np.int16)
    labels = np.full(mask.shape, 4, np.uint8)
    # Fabric and trousers derive primarily from color, rather than the generated
    # discrete masks, which are not perfectly aligned to the source character.
    pants = (red > green * 1.24) & (red > blue * 1.25) & (yy > height * .36) & (yy < height * .83)
    labels[pants] = 3
    tank = ((red - green) < 47) & ((green - blue) < 44) & (red > 110) & (maximum > 140) & (yy > .19*height) & (yy < .37*height) & (xx > .36*width) & (xx < .64*width)
    labels[tank] = 2
    skin = (red-green>27)&(green-blue>9)&(red>105)&(green>65)&(red>blue*1.28)&(yy<height*.55)
    labels[skin] = 1
    hair = (yy < height*.159) & (maximum < 153)
    labels[hair] = 5
    boots=(yy>height*.829)&(maximum<190)
    labels[boots] = 6
    labels[~mask] = 0
    # Despeckle only within coherent classes and preserve small buckle boundaries.
    return labels


def crop_generated(img):
    h,w = img.shape[:2]
    panels = {}
    for row, side in enumerate(('front','back')):
        for col, kind in enumerate(('albedo','normal','roughness','mask')):
            tile = img[round(row*h/2):round((row+1)*h/2),round(col*w/4):round((col+1)*w/4)].copy()
            panels[(side,kind)] = tile
            save_png(RAW/f'{side}_{kind}.png',tile)
    return panels


def generator_foreground(tile, is_mask=False):
    if is_mask:
        return (np.max(tile,axis=2)>42).astype(bool)
    return (np.min(tile,axis=2) < 228).astype(bool)


def row_mapping(mask_target, mask_generated):
    # Monotone y-registration combines edge-to-edge scaling with silhouette mass.
    H,W = mask_target.shape
    h,w = mask_generated.shape
    ttop, tbottom = np.nonzero(mask_target.any(axis=1))[0][[0,-1]]
    gtop, gbottom = np.nonzero(mask_generated.any(axis=1))[0][[0,-1]]
    ylinear = np.interp(np.arange(H),[ttop,tbottom],[gtop,gbottom]).astype(np.float32)
    # Cumulative mass stabilizes landmarks as pants and torso have very different widths.
    tcum = np.cumsum(mask_target.sum(axis=1).astype(float)+.001)
    gcum = np.cumsum(mask_generated.sum(axis=1).astype(float)+.001)
    tmass = np.interp(tcum/tcum[-1],gcum/gcum[-1],np.arange(h))
    yg = .8*ylinear+.2*tmass
    yg = np.maximum.accumulate(yg)
    yg = np.clip(yg,gtop,gbottom)
    return yg


def align_generator(tile, targetmask, generatormask, yg):
    H,W=targetmask.shape
    gh,gw=generatormask.shape
    xm=np.empty((H,W),np.float32)
    ym=np.broadcast_to(yg[:,None],(H,W)).astype(np.float32).copy()
    for y in range(H):
        gyi=int(np.clip(round(yg[y]),0,gh-1))
        ti=np.flatnonzero(targetmask[y]); gi=np.flatnonzero(generatormask[gyi])
        if len(ti)>1 and len(gi)>1:
            center_t=(ti[0]+ti[-1])*.5; center_g=(gi[0]+gi[-1])*.5
            extent_t=(ti[-1]-ti[0])*.5;extent_g=(gi[-1]-gi[0])*.5
            xm[y]=center_g+(np.arange(W)-center_t)*extent_g/max(1,extent_t)
        else:
            xm[y]=np.arange(W)*(gw-1)/max(1,W-1)
    return cv2.remap(tile,xm,ym,cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=(255,255,255))


def make_maps(front, back, panels):
    generated = {}
    validated = {}
    for side, source in [('front',front),('back',back)]:
        target = source_mask(source)
        source_raw = panels[(side,'albedo')]
        genmask = generator_foreground(source_raw)
        yg = row_mapping(target,genmask)
        aligned={kind:align_generator(panels[(side,kind)],target,genmask,yg) for kind in ('albedo','normal','roughness','mask')}
        # Generated material maps are registration candidates; the original image
        # is authoritative for local fine patterns and silhouette.
        for kind,arr in aligned.items():
            save_png(FINAL/f'{side}_{kind}_registered.png',arr)
        material = segment_material(source,target)
        # Use generated IDs only where a class is visually unambiguous; source
        # labels otherwise provide stability across front/back and preserve straps.
        gen_pixels=aligned['mask'].astype(np.float32)
        choices=np.argmin(((gen_pixels[:,:,None,:]-COLORS[None,None,:,:])**2).sum(axis=-1),axis=2)
        agreement=((choices==material)&target).sum()/max(1,target.sum())
        labels=material
        save_png(FINAL/f'{side}_mask.png', COLORS[labels])
        # Original painted artwork has illumination baked in. 90/10 blend avoids
        # generator's anatomical and equipment changes, and is explicitly recorded.
        sourcef=source.astype(np.float32)
        generatedf=aligned['albedo'].astype(np.float32)
        lab_source=cv2.cvtColor(source,cv2.COLOR_RGB2LAB)
        lab_generated=cv2.cvtColor(aligned['albedo'],cv2.COLOR_RGB2LAB)
        # Color matching by per-channel quantiles within the foreground.
        med0=np.median(sourcef[target],axis=0)
        med1=np.median(generatedf[target],axis=0)
        generatedf=np.clip(generatedf+(med0-med1)[None,None,:],0,255)
        albedo=np.where(target[:,:,None], .93*sourcef+.07*generatedf, np.full_like(sourcef,255))
        save_png(FINAL/f'{side}_albedo.png',albedo)
        # Remove low-frequency imagegen normals (they double-count mesh curvature).
        normal=aligned['normal'].astype(np.float32)/127.5-1.0
        detailed=normal[:,:,:2]-gaussian_filter(normal[:,:,:2],sigma=(10,10,0))
        detailed=np.clip(detailed*.33,-.36,.36)
        nz=np.sqrt(np.maximum(1.-np.square(detailed).sum(axis=2),.01))
        corrected=np.dstack((detailed,nz))
        normal_rgb=(corrected*0.5+0.5)*255.0
        normal_rgb[~target]=[128,128,255]
        save_png(FINAL/f'{side}_normal.png',normal_rgb)
        # The generated grayscale is a shaded render. Only its high frequency
        # variations are retained; material labels set the physical roughness.
        candidate=cv2.cvtColor(aligned['roughness'],cv2.COLOR_RGB2GRAY).astype(np.float32)/255.
        rough=ROUGHNESS[labels]+np.clip(candidate-gaussian_filter(candidate,7),-.045,.045)
        rough[~target]=1.0
        save_png(FINAL/f'{side}_roughness.png',rough*255)
        save_png(FINAL/f'{side}_silhouette.png',target.astype(np.uint8)*255)
        generated[side]={'albedo':albedo.astype(np.uint8),'normal':normal_rgb.astype(np.uint8),'roughness':np.clip(rough*255,0,255).astype(np.uint8),'mask':COLORS[labels],'labels':labels,'foreground':target}
        validated[side]={'foreground_pixels':int(target.sum()),'foreground_bounds':binary_bounds(target), 'source_generated_mask_agreement_fraction':float(agreement),'registered_generated_silhouette_iou':intersection_union(target, generator_foreground(aligned['albedo']))}
    return generated,validated


def build_volume(mask,height=384, step_size=2):
    # Radii are inferred from local front silhouette cross-sections; there are
    # no side-view depth measurements in two opposing A-pose photographs.
    H=int(height)
    W=round(H*mask.shape[1]/mask.shape[0])
    fg=cv2.resize(mask.astype(np.uint8),(W,H),interpolation=cv2.INTER_NEAREST)>0
    fg=cv2.morphologyEx(fg.astype(np.uint8),cv2.MORPH_CLOSE,np.ones((3,3),np.uint8)).astype(bool)
    D=round(W*.47)
    if D%2: D+=1
    coords=np.arange(D,dtype=np.float32)-(D-1)/2
    volume=np.full((H,W,D),-3.0,np.float32)
    xs=np.arange(W,dtype=np.float32)
    for y in range(H):
        row=np.pad(fg[y].astype(np.int8),1)
        starts=np.flatnonzero(np.diff(row)==1)
        stops=np.flatnonzero(np.diff(row)==-1)
        for left,right in zip(starts,stops):
            width=right-left
            if width<2: continue
            xc=.5*(right+left-1)
            radius=.5*width
            # Different anatomical bands permit different cross-sectional priors.
            if y<H*.165: ratio=.94         # head / hair
            elif y<H*.39: ratio=.76 if abs(xc-W/2)<W*.18 and width>W*.12 else .82
            elif y<H*.55: ratio=.72 if abs(xc-W/2)<W*.20 and width>W*.12 else .79
            elif y<H*.83: ratio=.78        # trousers
            else: ratio=.82                # boots
            # Avoid inflating a connected arm/torso junction into one huge tube.
            dz=np.clip(radius*ratio,1.3,W*.16)
            u=(xs[left:right]-xc)/max(radius,1)
            surface=dz*np.sqrt(np.maximum(0.,1.-np.square(u)))
            # Independently smooth adjacent tubes in z, then join via SDF.
            rowsurface=surface[:,None]-np.abs(coords[None,:])
            volume[y,left:right]=np.maximum(volume[y,left:right],rowsurface)
    volume=gaussian_filter(volume,(.85,.65,.65))
    volume = np.pad(volume, ((3, 3), (3, 3), (3, 3)), constant_values=-3.)
    vertices, faces, *_=marching_cubes(volume, level=0, step_size=step_size, allow_degenerate=False)
    vertices -= 3.
    # marching cubes uses image (y,x,z); world uses (+x,+y,+z front).
    scale=1.8/H
    world=np.column_stack(((vertices[:,1]-(W-1)/2)*scale,(H-1-vertices[:,0])*scale,(vertices[:,2]-(D-1)/2)*scale))
    mesh=trimesh.Trimesh(vertices=world,faces=faces,process=True)
    if mesh.volume<0: mesh.invert()
    if step_size>=2:
        trimesh.smoothing.filter_laplacian(mesh,lamb=.22,iterations=2,volume_constraint=False)
    return mesh,fg


def make_uv_atlas(maps,small=False):
    # GLB texture atlas: front = left half; back = right half.
    size=(256,384) if small else (512,768)
    atlases={}
    for kind in ('albedo','normal','roughness','mask'):
        tiles=[np.asarray(Image.fromarray(maps[side][kind]).resize(size,Image.Resampling.LANCZOS if kind=='albedo' else Image.Resampling.NEAREST)) for side in ('front','back')]
        atlas=np.concatenate(tiles,axis=1)
        if kind=='roughness': atlas=atlas.astype(np.uint8)
        atlases[kind]=atlas
        save_png(FINAL/f'atlas_{"preview" if small else "full"}_{kind}.png', atlas)
    orm=np.zeros((*atlases['roughness'].shape,3),np.uint8)
    orm[:,:,0]=255;orm[:,:,1]=atlases['roughness']
    atlases['orm']=orm
    save_png(FINAL/f'atlas_{"preview" if small else "full"}_orm.png',orm)
    return atlases


def texture_mesh(mesh,atlases,viewheight=1536):
    # One UV seam at z=0 separates front and rear projections. Back image x
    # must be reversed to correspond to a 180 degree rotated camera.
    faces=mesh.faces
    verts=mesh.vertices
    vertexNormals=mesh.vertex_normals.copy()
    chosen=(verts[faces,2].mean(axis=1)>=0).astype(np.uint8)
    indexed={}
    vlist=[];nlist=[];uvlist=[];flist=[]
    xnorm=verts[:,0]/1.8*viewheight/(viewheight*1024/1536)+.5  # cancels to 0.5+x / 1.2
    ynorm=verts[:,1]/1.8
    xnorm=np.clip(xnorm,0,1);ynorm=np.clip(ynorm,0,1)
    for i,face in enumerate(faces):
        side=int(chosen[i]);newface=[]
        for idx in face:
            key=(int(idx),side)
            if key not in indexed:
                indexed[key]=len(vlist)
                vlist.append(verts[idx]);nlist.append(vertexNormals[idx])
                u=xnorm[idx]*.5 if side else .5+(1.-xnorm[idx])*.5
                uvlist.append([float(np.clip(u,.001,.999)),float(ynorm[idx])])
            newface.append(indexed[key])
        flist.append(newface)
    rendered=trimesh.Trimesh(vertices=np.asarray(vlist), faces=np.asarray(flist), vertex_normals=np.asarray(nlist),process=False)
    material=PBRMaterial(name='Kiku aligned maps',baseColorFactor=[255,255,255,255],baseColorTexture=Image.fromarray(atlases['albedo']),normalTexture=Image.fromarray(atlases['normal']),metallicRoughnessTexture=Image.fromarray(atlases['orm']),roughnessFactor=1.0,metallicFactor=1.0,doubleSided=True)
    rendered.visual=TextureVisuals(uv=np.asarray(uvlist),material=material)
    return rendered


def project_mask(mesh, height, angle=0):
    width=round(height*1024/1536)
    result=np.zeros((height,width),np.uint8)
    pos=mesh.vertices.copy()
    angle=math.radians(angle)
    xx=pos[:,0]*math.cos(angle)+pos[:,2]*math.sin(angle)
    yy=pos[:,1]
    physical_width=1.8*width/height
    points=np.column_stack(((xx/physical_width+.5)*width,(1-yy/1.8)*height)).astype(np.int32)
    for face in mesh.faces:
        cv2.fillConvexPoly(result,points[face],255)
    return result>0


def render(mesh,textures,angle,shape=(750,500)):
    height,width=shape
    rendered=np.full((height,width,3),245,np.uint8)
    radians=math.radians(angle)
    verts=mesh.vertices
    X=verts[:,0]*math.cos(radians)+verts[:,2]*math.sin(radians)
    Z=verts[:,2]*math.cos(radians)-verts[:,0]*math.sin(radians)
    xx=(X/(1.8*width/height)+.5)*width
    yy=(1.-verts[:,1]/1.8)*height
    points=np.stack((xx,yy),axis=-1).astype(np.int32)
    faces=mesh.faces
    depth=Z[faces].mean(axis=1)
    tri=verts[faces]
    normals=np.cross(tri[:,1]-tri[:,0],tri[:,2]-tri[:,0])
    normals/=np.maximum(np.linalg.norm(normals,axis=1,keepdims=True),1e-6)
    light=np.array([.35,.65,1]);light/=np.linalg.norm(light)
    lighting=np.clip((normals@light)*.45+.68,.55,1.12)
    ref_front=textures['front']['albedo'];ref_back=textures['back']['albedo']
    h,w=ref_front.shape[:2]
    mid=tri.mean(axis=1)
    front_side=(normals[:,2]>0)
    sx=np.clip(((mid[:,0]/1.8*1536/1024+.5)*(w-1)).astype(int),0,w-1)
    sy=np.clip(((1-mid[:,1]/1.8)*(h-1)).astype(int),0,h-1)
    color=np.empty((len(faces),3),np.uint8)
    color[front_side]=ref_front[sy[front_side],sx[front_side]]
    color[~front_side]=ref_back[sy[~front_side],(w-1-sx[~front_side])]
    color=np.clip(color*lighting[:,None],0,255).astype(np.uint8)
    for index in np.argsort(depth):
        if np.dot(normals[index],np.array([-math.sin(radians),0,math.cos(radians)]))<-.12:continue
        cv2.fillConvexPoly(rendered,points[faces[index]],tuple(int(x) for x in color[index]))
    return rendered


def main():
    original_front=np.asarray(Image.open(FRONT).convert('RGB'))
    original_back=np.asarray(Image.open(BACK).convert('RGB'))
    sheet=np.asarray(Image.open(GENERATED).convert('RGB'))
    panels=crop_generated(sheet)
    maps,evidence=make_maps(original_front,original_back,panels)
    maskFront=maps['front']['foreground'];maskBack=maps['back']['foreground']
    alignedBack,affine,score=register_back(maskFront,maskBack)
    before=intersection_union(maskFront,np.fliplr(maskBack))
    after=intersection_union(maskFront,alignedBack)
    # Geometry remains faithful to original front silhouette. Back constrains
    # disparities but does not distort it to one synthetic averaged target.
    print('build coarse',flush=True)
    coarse,coarsemask=build_volume(maskFront,height=288,step_size=2)
    print('build fine',flush=True)
    fine,finemask=build_volume(maskFront,height=384,step_size=2)
    print('build atlases',flush=True)
    atlasSmall=make_uv_atlas(maps,small=True)
    atlasFull=make_uv_atlas(maps,small=False)
    print('texture meshes',flush=True)
    previewMesh=texture_mesh(coarse,atlasSmall)
    fullMesh=texture_mesh(fine,atlasFull)
    print('export',flush=True)
    previewMesh.export(BASE/'kiku_pbr_preview.glb',file_type='glb')
    fullMesh.export(BASE/'kiku_pbr_full.glb',file_type='glb')
    fine.export(BASE/'kiku_surface.stl')
    print('render',flush=True)
    for k,a in [('front',0),('three_quarter',45),('side',90),('back',180)]:
        save_png(BASE/f'render_{k}.png',render(coarse,maps,a))
    from PIL import ImageDraw
    figures=[Image.open(BASE/f'render_{key}.png') for key in ('front','three_quarter','side','back')]
    contact=Image.new('RGB',(figures[0].width*4,figures[0].height),'white')
    for i,im in enumerate(figures):contact.paste(im,(i*im.width,0))
    contact.save(BASE/'renders.webp',quality=88)
    # Compare mesh silhouette to BOTH originals. Projection IoU is a held-out
    # rasterization check of the resulting mesh against the source masks.
    projectedFront=project_mask(coarse,384,0)
    projectedBack=project_mask(coarse,384,180)
    sourceFront=cv2.resize(maskFront.astype(np.uint8),(256,384),interpolation=cv2.INTER_NEAREST)>0
    sourceBack=cv2.resize(maskBack.astype(np.uint8),(256,384),interpolation=cv2.INTER_NEAREST)>0
    results={
        'reference_size':[1024,1536],
        'generated_sheet_size':list(Image.open(GENERATED).size),
        'front_back_iou_raw':before,
        'front_back_iou_affine_registered':after,
        'affine_back_on_front':affine.tolist(),
        'registration_ecc':None if score is None else float(score),
        'mesh_projection_front_iou':intersection_union(sourceFront,projectedFront),
        'mesh_projection_back_iou':intersection_union(sourceBack,projectedBack),
        'preview_vertices':int(len(previewMesh.vertices)),
        'preview_faces':int(len(previewMesh.faces)),
        'full_vertices':int(len(fullMesh.vertices)),
        'full_faces':int(len(fullMesh.faces)),
        'preview_watertight_before_uv_seam':bool(coarse.is_watertight),
        'full_watertight_before_uv_seam':bool(fine.is_watertight),
        'body_height_m_assumption':1.8,
        'depth_assumption':'row-wise elliptical inflation; no measured depth or side-view constraint',
        'albedo':'93% original stylized image and 7% color-matched generator, retains baked illustration shadows',
        'roughness':'material-class values with generator residual capped at +/- .045',
        'normal':'generator view-space normals: high-pass and 0.33 amplitude, baked as approximate tangent perturbation',
        'source_maps': evidence,
        'material_classes':dict(zip(MATERIAL_NAMES,ROUGHNESS.tolist())),
        'status':'experimental, non-rigged, two-view inferred geometry',
    }
    (BASE/'metrics.json').write_text(json.dumps(results,indent=2)+'\n')
    print(json.dumps(results,indent=2))

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--front',type=Path,default=FRONT)
    parser.add_argument('--back',type=Path,default=BACK)
    parser.add_argument('--generated',type=Path,default=GENERATED)
    parser.add_argument('--output',type=Path,default=BASE)
    args = parser.parse_args()
    FRONT, BACK, GENERATED, BASE = args.front, args.back, args.generated, args.output
    RAW, FINAL = BASE / 'generator', BASE / 'maps'
    BASE.mkdir(parents=True,exist_ok=True)
    RAW.mkdir(parents=True,exist_ok=True)
    FINAL.mkdir(parents=True,exist_ok=True)
    main()
