import cv2
import numpy as np
import glob
import os

template = cv2.imread("captures/traverse_modal_crop.png")
th, tw = template.shape[:2]

for f in sorted(glob.glob("captures/*.png")):
    if "crop" in f or "thumb" in f or "after_traverse" in f:
        continue
    img = cv2.imread(f)
    if img is None or img.shape[0] != 1440 or img.shape[1] != 2560:
        continue
    
    # Template match on a small sub-crop of the template (e.g. the TRAVERSE button)
    btn_crop = template[int(th*0.5):, :]
    bh, bw = btn_crop.shape[:2]
    res = cv2.matchTemplate(img, btn_crop, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if max_val > 0.8:
        print(f"Match found in {f} with score {max_val:.3f} at top-left {max_loc}")
        btn_center_x = max_loc[0] + bw // 2
        btn_center_y = max_loc[1] + bh // 2
        print(f"TRAVERSE button center in 2560x1440: ({btn_center_x}, {btn_center_y})")
        break
