import numpy as np, cv2, os, glob

W = "/Users/danicosta/Desktop/AI-Instagram/_inpaint"
full_dir = f"{W}/frames_full"
inp_dir  = f"{W}/results/frames_crop/frames"
out_dir  = f"{W}/frames_out"
os.makedirs(out_dir, exist_ok=True)

X0, Y0 = 336, 896          # esquina sup-izq del recorte en el cuadro completo
CW = CH = 384

# Mascara del recorte (caja sobre la marca) -> alpha difuminada
mask = cv2.imread(f"{W}/mask.png", cv2.IMREAD_GRAYSCALE)
assert mask.shape == (CH, CW), mask.shape
k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))
md = cv2.dilate(mask, k, iterations=1)
alpha = cv2.GaussianBlur(md.astype(np.float32), (0, 0), sigmaX=4.0) / 255.0
alpha = np.clip(alpha, 0.0, 1.0)[..., None]   # 384x384x1

fulls = sorted(glob.glob(f"{full_dir}/*.png"))
inps  = sorted(glob.glob(f"{inp_dir}/*.png"))
assert len(fulls) == len(inps) == 240, (len(fulls), len(inps))

for i, (fp, ip) in enumerate(zip(fulls, inps)):
    full = cv2.imread(fp)                 # 1280x720x3 BGR
    inp  = cv2.imread(ip)                 # 384x384x3 BGR (reconstruido)
    assert inp.shape == (CH, CW, 3), inp.shape
    region = full[Y0:Y0+CH, X0:X0+CW].astype(np.float32)
    blend  = region * (1.0 - alpha) + inp.astype(np.float32) * alpha
    full[Y0:Y0+CH, X0:X0+CW] = np.clip(blend, 0, 255).astype(np.uint8)
    cv2.imwrite(f"{out_dir}/{i+1:05d}.png", full)

print("composited", len(fulls), "frames ->", out_dir)
