import cv2
import numpy as np
import time

img0 = cv2.imread(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\raw_chunk_00.png")
img1 = cv2.imread(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\raw_chunk_01.png")

gray0 = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY)
gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)

w = gray0.shape[1]

best_ov = 0
min_mad = float('inf')

start_time = time.time()
# Downsample by 2 horizontally & vertically for extreme speed
small0 = cv2.resize(gray0, (w//2, gray0.shape[0]//2))
small1 = cv2.resize(gray1, (w//2, gray1.shape[0]//2))
sw = small0.shape[1]

# We are testing overlap pixel widths
for ov in range(sw-2, 10, -1):
    diff = cv2.absdiff(small0[:, -ov:], small1[:, :ov])
    mad = np.mean(diff)
    
    if mad < min_mad:
        min_mad = mad
        best_ov = ov * 2 # map back to original scale
        
    if min_mad < 3.0: # Break early if effectively a perfect match!
        best_ov = ov * 2
        break

end_time = time.time()
print(f"MSE MAD found overlap {best_ov}px with MAD {min_mad:.2f} in {(end_time-start_time)*1000:.1f}ms")

# Verify
stitched = np.hstack([img0, img1[:, best_ov:]])
cv2.imwrite(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\test_mse_stitch.png", stitched)
print("Exported test_mse_stitch.png")
