import cv2
import numpy as np

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)

h, w = gray0.shape

# The first 300px of img1 is our template
template_w = 400
template = gray1[:60, :template_w] # ONLY TOP 60 PIXELS
ref = gray0[:60, :] # ONLY TOP 60 PIXELS

# Find where 'template' is in 'gray0'
res = cv2.matchTemplate(ref, template, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(res)

print(f"Match value (Top 60px): {max_val:.3f}")
if max_val > 0.8:
    match_x_in_last = max_loc[0]
    overlap_len = w - match_x_in_last
    print(f"Overlap starts in last_chunk at x={match_x_in_last}.")
    print(f"Length of overlap is {overlap_len}px.")
    
    if overlap_len < w:
        new_slice = img1[:, overlap_len:]
        stitched = np.hstack([img0, new_slice])
        cv2.imwrite(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\test_stitched_top60.png", stitched)
        print("Exported test_stitched_top60.png")
else:
    print("No valid overlap found.")
    

