"""Relight a single photo: MoGe-2 point map + Marigold albedo -> mesh seen from the photo's own camera,
lit with Geoff Boyle's one-redhead kit in Cycles.

Usage:
  blender -b --factory-startup --python photo_relight.py -- --est /work/renders/photo/est --pass boyle --out x.png
Passes:
  albedo   flat white light, no shadows: what the de-lit texture looks like
  direct   redhead straight at the face from beside the camera
  boyle    redhead into poly over the camera + black flags either side (the beauty setup)
  side     hard redhead from the left at 80 degrees: tests shadows the photo never had
  geometry grey clay render of the recovered mesh, lit like boyle
"""
import argparse, json, math, sys
import numpy as np
import bpy
from mathutils import Vector

argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
ap = argparse.ArgumentParser()
ap.add_argument("--est", required=True)
ap.add_argument("--pass", dest="pas", default="boyle", choices=["albedo", "direct", "boyle", "side", "geometry"])
ap.add_argument("--out", required=True)
ap.add_argument("--samples", type=int, default=128)
ap.add_argument("--exposure", type=float, default=0.0)
ap.add_argument("--step", type=int, default=2, help="mesh every Nth pixel")
ap.add_argument("--graze", type=float, default=0.0, help="drop faces whose normal is within this cosine of edge-on")
ap.add_argument("--normals", type=int, default=1, help="1 = shade with MoGe-2 normals")
ap.add_argument("--orbit", type=float, default=0.0, help="degrees to swing the camera around the head")
ap.add_argument("--jump", type=float, default=1.10, help="don't join neighbours whose depths differ by more than this ratio")
ap.add_argument("--dist", type=float, default=0.92, help="camera-to-head distance after rescaling, m (0 = keep the model's guess)")
ap.add_argument("--mask", default="moge", choices=["moge", "depth"],
                help="moge: the model's own mask; depth: also split subject from a near backdrop at the biggest depth gap")
ap.add_argument("--albedo", default="albedo.png", help="albedo file in --est (albedo_detail.png = detail restored)")
ap.add_argument("--material", default="marble", choices=["marble", "skin"])
ap.add_argument("--flame", default="", help="fit.npz from flame_fit.py: use the fitted FLAME head instead of the per-pixel mesh")
ap.add_argument("--detail-normals", type=float, default=0.0,
                help="FLAME only: add this much of normal_detail.png (photo's fine creases) to the head's own normals")
ap.add_argument("--transparent", type=int, default=0, help="1 = transparent background (for overlays)")
ap.add_argument("--save-blend", default="")
a = ap.parse_args(argv)

bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene
E = a.est

# ---------------------------------------------------------------- load estimates
P = np.load(f"{E}/points.npy")           # OpenCV camera frame: x right, y down, z forward (metres)
valid = np.load(f"{E}/mask.npy").astype(bool) & np.isfinite(P).all(-1)
meta = json.load(open(f"{E}/intrinsics.json")); K = np.array(meta["K"]); W, H = meta["W"], meta["H"]
z = np.where(valid, P[..., 2], np.nan)

# foreground: MoGe-2's own mask drops sky-like background; keep its largest connected blob.
# In a studio portrait the backdrop is close and survives that mask, so --mask depth also splits on depth (Otsu on log z).
fg = valid.copy()
if a.mask == "depth":
    lz = np.log(z[valid]); hist, edges = np.histogram(lz, 256)
    w0 = np.cumsum(hist); w1 = w0[-1] - w0; m_ = np.cumsum(hist * edges[:-1])
    mu0 = m_ / np.maximum(w0, 1); mu1 = (m_[-1] - m_) / np.maximum(w1, 1)
    thr = np.exp(edges[np.argmax(w0 * w1 * (mu0 - mu1) ** 2)])
    fg &= z < thr
    print(f"depth split at {thr:.2f} m (model units)", flush=True)
from collections import deque
lab = np.zeros(fg.shape, np.int32); best, bestn, cur = 0, 0, 0
for sy, sx in zip(*np.nonzero(fg[::8, ::8])):
    sy, sx = sy * 8, sx * 8
    if lab[sy, sx]: continue
    cur += 1; n = 0; q = deque([(sy, sx)]); lab[sy, sx] = cur
    while q:
        y, x = q.popleft(); n += 1
        for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            yy, xx = y + dy, x + dx
            if 0 <= yy < H and 0 <= xx < W and fg[yy, xx] and not lab[yy, xx]:
                lab[yy, xx] = cur; q.append((yy, xx))
    if n > bestn: best, bestn = cur, n
fg = lab == best
# scale: one photo can't tell size. Rescale about the camera (the view is unchanged) so the head sits --dist metres away.
rows = np.nonzero(fg.any(1))[0]; head_rows = slice(rows[0], rows[0] + int(0.35 * (rows[-1] - rows[0])))
hd = np.median(P[head_rows][fg[head_rows]][:, 2])
if a.flame:                                    # FLAME is metric: put the body mesh at the fitted head's distance
    _fz = np.load(a.flame); a.dist = float(np.linalg.norm(_fz["verts"].mean(0)))
    fg &= ~_fz["headmask"]                     # the head itself comes from FLAME
SCALE = a.dist / hd if a.dist > 0 else 1.0
P = P * SCALE; z = P[..., 2]
print(f"foreground {fg.mean():.1%} of pixels; head at {hd:.2f} m as estimated, rescaled x{SCALE:.3f} to {hd*SCALE:.2f} m", flush=True)

# ---------------------------------------------------------------- mesh (Blender camera frame = OpenCV with y, z flipped)
S = a.step
ys, xs = np.arange(0, H, S), np.arange(0, W, S)
idx = -np.ones((len(ys), len(xs)), np.int64); verts, uvs = [], []
for i, y in enumerate(ys):
    for j, x in enumerate(xs):
        if fg[y, x]:
            px, py, pz = P[y, x]
            idx[i, j] = len(verts); verts.append((px, -py, -pz)); uvs.append(((x + 0.5) / W, 1 - (y + 0.5) / H))
faces = []
zz = z
for i in range(len(ys) - 1):
    for j in range(len(xs) - 1):
        q = (idx[i, j], idx[i, j + 1], idx[i + 1, j + 1], idx[i + 1, j])
        if min(q) < 0: continue
        d = [zz[ys[i], xs[j]], zz[ys[i], xs[j + 1]], zz[ys[i + 1], xs[j + 1]], zz[ys[i + 1], xs[j]]]
        if max(d) / min(d) > a.jump: continue          # don't bridge big depth jumps (the bust edge against the plinth etc.)
        # drop faces nearly edge-on to the camera: they are stretched across the silhouette, where
        # one photo has no information, and grazing light shows them up as streaks
        pa, pb, pc_ = (P[ys[i], xs[j]], P[ys[i], xs[j + 1]], P[ys[i + 1], xs[j]])
        nrm = np.cross(pb - pa, pc_ - pa); ray = pa / np.linalg.norm(pa)
        if abs(np.dot(nrm, ray)) < a.graze * np.linalg.norm(nrm): continue
        faces.append((q[0], q[3], q[2], q[1]))       # wound to face the camera
me = bpy.data.meshes.new("photo_mesh"); me.from_pydata(verts, [], faces); me.update()
uvl = me.uv_layers.new(name="UV")
for poly in me.polygons:
    for li in poly.loop_indices:
        uvl.data[li].uv = uvs[me.loops[li].vertex_index]
for p in me.polygons: p.use_smooth = True
# shade with MoGe-2's predicted normals rather than normals of the stepped depth mesh
import os
if a.normals and os.path.exists(f"{E}/normal.npy"):
    Nm = np.load(f"{E}/normal.npy")
    vn = []
    for i, y in enumerate(ys):
        for j, x in enumerate(xs):
            if idx[i, j] >= 0:
                nx, ny, nz = Nm[y, x]; v = np.array((nx, -ny, -nz)); v /= (np.linalg.norm(v) + 1e-9)
                vn.append(tuple(v))
    me.normals_split_custom_set_from_vertices(vn)
obj = bpy.data.objects.new("subject", me); scn.collection.objects.link(obj)
print(f"mesh {len(verts)} verts {len(faces)} faces", flush=True)

V = np.array(verts); top = V[V[:, 1] > np.percentile(V[:, 1], 70)]       # head region
C = Vector(np.median(top, axis=0)); dist = -C.z

FILL = None
if a.flame:
    # replace the per-pixel relief with the fitted FLAME head (metres, so no rescale)
    body = obj; body.name = "body"; fz = np.load(a.flame)
    X = fz["verts"]; Fc = fz["faces"]; fx_, fy_ = K[0, 0] * W, K[1, 1] * H; cx_, cy_ = K[0, 2] * W, K[1, 2] * H
    vb = [(x, -y, -z_) for x, y, z_ in X]
    Fk = Fc[fz["keep"]]
    me = bpy.data.meshes.new("flame"); me.from_pydata(vb, [], [tuple(f) for f in Fk]); me.update()
    for p_ in me.polygons: p_.use_smooth = True
    obj = bpy.data.objects.new("subject", me); scn.collection.objects.link(obj)
    # photo projected as UVs
    uvp = [((fx_ * x / z_ + cx_) / W, 1 - (fy_ * y / z_ + cy_) / H) for x, y, z_ in X]
    uvl = me.uv_layers.new(name="UV")
    for poly in me.polygons:
        for li in poly.loop_indices:
            uvl.data[li].uv = uvp[me.loops[li].vertex_index]
    # which vertices the camera saw: facing it and not hidden behind another part of the head
    from mathutils.bvhtree import BVHTree
    bvh = BVHTree.FromPolygons([Vector(v) for v in vb], [tuple(f) for f in Fk])
    vis = np.zeros(len(vb), np.float32)
    for i, v in enumerate(me.vertices):
        P0 = v.co; to_cam = -P0.normalized()
        facing = v.normal.dot(to_cam)
        if facing < 0.1: continue
        hit = bvh.ray_cast(Vector((0, 0, 0)), P0.normalized(), P0.length - 1e-3)
        if hit[0] is None:
            vis[i] = min(1.0, (facing - 0.1) / 0.3)               # fade out toward grazing angles
    att = me.color_attributes.new("vis", "FLOAT_COLOR", "POINT")
    for i, w in enumerate(vis): att.data[i].color = (w, w, w, 1)
    # unseen skin gets the median colour of the seen skin
    img = bpy.data.images.load(f"{E}/{a.albedo}"); px = np.array(img.pixels[:], np.float32).reshape(img.size[1], img.size[0], 4)
    seen = [(u, v_) for (u, v_), w in zip(uvp, vis) if w > 0.9]
    cols = np.array([px[min(int(v_ * img.size[1]), img.size[1] - 1), min(int(u * img.size[0]), img.size[0] - 1), :3] for u, v_ in seen])
    FILL = tuple(np.median(cols, axis=0)) + (1.0,)
    obj.modifiers.new("subd", "SUBSURF").levels = 2; obj.modifiers["subd"].render_levels = 2
    V = np.array(vb); C = Vector(V.mean(0)); dist = -C.z
    print(f"FLAME head: {int((vis > 0.9).sum())}/{len(vis)} vertices seen by the camera; fill colour {np.round(FILL[:3], 3)}", flush=True)
print(f"head centre {tuple(round(c, 3) for c in C)}, {dist:.2f} m from camera", flush=True)

# ---------------------------------------------------------------- material
def make_material(name, fill=None, sss_scale=None):
    """Albedo-textured surface. With fill: unseen parts (vertex attribute 'vis' = 0) get the fill colour."""
    mat = bpy.data.materials.new(name); mat.use_nodes = True; nt = mat.node_tree; b = nt.nodes["Principled BSDF"]
    if fill is not None and a.detail_normals > 0:
        # fine creases from the photo: geometric normal + k * high-pass(MoGe normals), only where the camera saw
        dn = nt.nodes.new("ShaderNodeTexImage"); dn.image = bpy.data.images.load(f"{E}/normal_detail.png")
        dn.image.colorspace_settings.name = "Non-Color"; dn.extension = "EXTEND"
        sub = nt.nodes.new("ShaderNodeVectorMath"); sub.operation = "SUBTRACT"; sub.inputs[1].default_value = (0.5, 0.5, 0.5)
        vis_d = nt.nodes.new("ShaderNodeVertexColor"); vis_d.layer_name = "vis"
        k = nt.nodes.new("ShaderNodeMath"); k.operation = "MULTIPLY"; k.inputs[1].default_value = a.detail_normals
        sc = nt.nodes.new("ShaderNodeVectorMath"); sc.operation = "SCALE"
        geo = nt.nodes.new("ShaderNodeNewGeometry")
        add = nt.nodes.new("ShaderNodeVectorMath"); add.operation = "ADD"
        nrm = nt.nodes.new("ShaderNodeVectorMath"); nrm.operation = "NORMALIZE"
        L = nt.links
        L.new(dn.outputs["Color"], sub.inputs[0]); L.new(vis_d.outputs["Fac"] if "Fac" in vis_d.outputs else vis_d.outputs["Color"], k.inputs[0])
        L.new(sub.outputs["Vector"], sc.inputs[0]); L.new(k.outputs["Value"], sc.inputs["Scale"])
        L.new(geo.outputs["Normal"], add.inputs[0]); L.new(sc.outputs["Vector"], add.inputs[1])
        L.new(add.outputs["Vector"], nrm.inputs[0]); L.new(nrm.outputs["Vector"], b.inputs["Normal"])
    if a.pas == "geometry":
        b.inputs["Base Color"].default_value = (0.6, 0.6, 0.6, 1); b.inputs["Roughness"].default_value = 0.6
        return mat
    t = nt.nodes.new("ShaderNodeTexImage"); t.image = bpy.data.images.load(f"{E}/{a.albedo}")
    t.extension = "EXTEND"
    if fill is not None:
        ca = nt.nodes.new("ShaderNodeVertexColor"); ca.layer_name = "vis"
        mix = nt.nodes.new("ShaderNodeMix"); mix.data_type = "RGBA"
        mix.inputs["A"].default_value = fill
        nt.links.new(ca.outputs["Color"], mix.inputs["Factor"]); nt.links.new(t.outputs["Color"], mix.inputs["B"])
        nt.links.new(mix.outputs["Result"], b.inputs["Base Color"])
    else:
        nt.links.new(t.outputs["Color"], b.inputs["Base Color"])
    if a.material == "skin":
        b.inputs["Roughness"].default_value = 0.42
        b.inputs["Subsurface Weight"].default_value = 0.6       # skin: light travels mm under the surface,
        b.inputs["Subsurface Radius"].default_value = (1.0, 0.35, 0.2)   # red furthest
        b.inputs["Subsurface Scale"].default_value = sss_scale or 0.005
        b.inputs["Specular IOR Level"].default_value = 0.5
    else:
        b.inputs["Roughness"].default_value = 0.45              # honed marble
        b.inputs["Subsurface Weight"].default_value = 0.25      # marble lets light in a few mm
        b.inputs["Subsurface Radius"].default_value = (1.0, 0.9, 0.8)
        b.inputs["Subsurface Scale"].default_value = sss_scale or 0.004
    return mat

if FILL is not None:
    # FLAME's eyelids are thin shells: a long scattering radius makes them glow, so keep it at 2 mm
    obj.data.materials.append(make_material("head", FILL, 0.002))
    body.data.materials.append(make_material("body"))
else:
    obj.data.materials.append(make_material("surface"))

def look_at(o, tgt, up=Vector((0, 1, 0))):
    """Point local -Z at tgt with local +Y toward world +Y (this scene keeps the photo's up = +Y)."""
    from mathutils import Matrix
    zc = (o.location - Vector(tgt)).normalized(); xc = up.cross(zc).normalized(); yc = zc.cross(xc)
    o.rotation_euler = Matrix((xc, yc, zc)).transposed().to_euler()

# ---------------------------------------------------------------- camera: the photo's own
cd = bpy.data.cameras.new("cam"); cam = bpy.data.objects.new("cam", cd); scn.collection.objects.link(cam)
scn.camera = cam; cd.sensor_fit = "HORIZONTAL"; cd.sensor_width = 36; cd.lens = K[0, 0] * 36
cd.clip_start = 0.01
if a.orbit:
    # swing the camera around the head to show what one photo does not contain
    from mathutils import Matrix
    R = Matrix.Rotation(math.radians(a.orbit), 4, "Y")
    cam.location = C + (R @ (Vector((0, 0, 0)) - C)); look_at(cam, C)

# ---------------------------------------------------------------- kit (positions relative to the head and camera)
def diffuse(name, alb):
    m = bpy.data.materials.new(name); m.use_nodes = True; bb = m.node_tree.nodes["Principled BSDF"]
    bb.inputs["Base Color"].default_value = (*alb, 1); bb.inputs["Roughness"].default_value = 1.0
    bb.inputs["Specular IOR Level"].default_value = 0.1; return m
def board(name, size, loc, tgt, m):
    bpy.ops.mesh.primitive_plane_add(size=1, location=loc); o = bpy.context.active_object; o.name = name
    o.scale = (size[0], size[1], 1); look_at(o, tgt); o.rotation_euler.rotate_axis("X", math.pi)
    o.data.materials.append(m); o.modifiers.new("t", "SOLIDIFY").thickness = 0.01; return o
def redhead(loc, tgt, deg):
    ld = bpy.data.lights.new("redhead", "SPOT"); ld.energy = 96; ld.spot_size = math.radians(deg)
    ld.spot_blend = 0.3; ld.shadow_soft_size = 0.03; ld.use_nodes = True
    bbn = ld.node_tree.nodes.new("ShaderNodeBlackbody"); bbn.inputs[0].default_value = 3200
    ld.node_tree.links.new(bbn.outputs[0], ld.node_tree.nodes["Emission"].inputs["Color"])
    o = bpy.data.objects.new("redhead", ld); scn.collection.objects.link(o); o.location = loc; look_at(o, tgt)

up, toward = Vector((0, 1, 0)), Vector((0, 0, 1))      # camera frame: +y up, +z back toward camera
if a.pas == "albedo":
    scn.world = bpy.data.worlds.new("white"); scn.world.color = (1, 1, 1)
else:
    scn.world = bpy.data.worlds.new("black"); scn.world.color = (0, 0, 0)
    room = diffuse("studio", (0.18, 0.18, 0.18))
    bpy.ops.mesh.primitive_cube_add(size=1, location=C + Vector((0, 0.5, 0.5)))
    r = bpy.context.active_object; r.scale = (7, 4, 9); r.modifiers.new("t", "SOLIDIFY").thickness = 0.05
    r.data.materials.append(room)
    board("backdrop", (4, 3), C + Vector((0, 0, -1.2)), C, diffuse("backdrop", (0.035, 0.035, 0.04)))
    poly, flag = diffuse("poly", (0.92, 0.92, 0.9)), diffuse("duvetyne", (0.025, 0.025, 0.025))
    if a.pas == "direct":
        redhead(Vector((0.35, 0.15, 0.2)), C, 40)
    elif a.pas == "side":
        redhead(C + Vector((-1.4, 0.35, 0.25)), C, 30)
    else:   # boyle and geometry
        pc = Vector((0, 0.55, 0.15))                           # poly over the camera
        board("poly_over_camera", (1.2, 1.2), pc, C + Vector((0, -0.1 * dist, 0)), poly)
        redhead(C + toward * (0.35 * dist) + Vector((0, -1.0, 0)), pc, 55)
        for side in (-1, 1) if not a.orbit else ():     # an orbiting camera would sit behind a flag
            c = C + Vector((side * 0.25, -0.02, 0.3 * dist))
            board(f"flag{side}", (0.5, 0.9), c, c + Vector((-side, 0, -0.15)), flag)

# ---------------------------------------------------------------- render
scn.render.engine = "CYCLES"; scn.cycles.device = "CPU"; scn.cycles.samples = a.samples
scn.cycles.use_denoising = True
scn.render.resolution_x, scn.render.resolution_y = W, H
scn.view_settings.view_transform = "AgX"; scn.view_settings.look = "AgX - Base Contrast"
scn.view_settings.exposure = a.exposure
if a.pas == "albedo":
    scn.view_settings.view_transform = "Standard"; scn.view_settings.look = "None"
else:
    scn.view_settings.use_white_balance = True; scn.view_settings.white_balance_temperature = 3200
scn.render.film_transparent = bool(a.transparent)
scn.render.filepath = a.out
if a.save_blend: bpy.ops.wm.save_as_mainfile(filepath=a.save_blend)
bpy.ops.render.render(write_still=True)
print("WROTE", a.out, flush=True)
