import cv2
import numpy as np

def test_page_flip_diff():
    import glob
    videos = glob.glob("output/*.mp4")
    cap = cv2.VideoCapture(videos[0] if videos else "output/shintakarajima.mp4")
    ret, prev_frame = cap.read()
    if not ret: return
    scale = 1280 / prev_frame.shape[1]
    prev = cv2.resize(prev_frame, (1280, int(prev_frame.shape[0] * scale)))[103:280, :]
    prev_gray = cv2.cvtColor(prev, cv2.COLOR_BGR2GRAY)
    
    idx = 1
    max_diff = 0
    max_diff_idx = -1
    
    print("Scanning first 2000 frames for diff_ratio spikes...")
    while idx < 2000:
        ret, frame = cap.read()
        if not ret: break
        
        # Only check every frame
        curr = cv2.resize(frame, (1280, int(frame.shape[0] * scale)))[103:280, :]
        curr_gray = cv2.cvtColor(curr, cv2.COLOR_BGR2GRAY)
        
        diff = cv2.absdiff(prev_gray, curr_gray)
        _, thresh = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY)
        ratio = np.sum(thresh > 0) / thresh.size
        
        if ratio > 0.01:
            print(f"Frame {idx}: diff_ratio = {ratio:.4f}")
            
        if ratio > max_diff:
            max_diff = ratio
            max_diff_idx = idx
            
        prev_gray = curr_gray
        idx += 1
        
    print(f"\nMax diff spike: {max_diff:.4f} at frame {max_diff_idx}")

if __name__ == "__main__":
    test_page_flip_diff()
