import cv2
import numpy as np
import glob

videos = glob.glob('output/*.mp4')
cap = cv2.VideoCapture(videos[0])

# Collect 30 continuous frames (about 1 second of video)
frames = []
cap.set(cv2.CAP_PROP_POS_FRAMES, 500)
for _ in range(30):
    ret, frame = cap.read()
    if not ret: break
    frames.append(frame)
cap.release()

if len(frames) == 30:
    # 1. Temporal Median to completely erase the live-action moving guitarist and background
    median_frame = np.median(frames, axis=0).astype(np.uint8)
    
    gray = np.max(median_frame, axis=2)
    _, binary = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)
    
    # 2. Extract true staff lines from the pristine static overlay
    row_sums = np.sum(binary, axis=1) / 255
    y_staff = np.where(row_sums > binary.shape[1] * 0.4)[0]
    
    if len(y_staff) > 0:
        print(f"Pristine staff lines detected at: {y_staff}")
        y_top = y_staff[0]
        y_bottom = y_staff[-1]
        
        # 3. Extract vertical bars perfectly
        roi = binary[y_top:y_bottom, :]
        col_sums = np.sum(roi, axis=0) / 255
        
        staff_h = y_bottom - y_top
        bars = np.where(col_sums > staff_h * 0.5)[0]
        
        clean_bars = []
        for x in bars:
            if not clean_bars or x - clean_bars[-1] > 20:
                clean_bars.append(int(x))
                
        print(f"Pristine Measure Boundaries: {clean_bars}")
        
    cv2.imwrite("C:/Users/Certes/Desktop/guitar_score/debug_temporal_median.png", median_frame)
    cv2.imwrite("C:/Users/Certes/Desktop/guitar_score/debug_temporal_binary.png", binary)
else:
    print("Not enough frames.")
