import cv2
import numpy as np
import os

img_path = r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\final_check_100_sec.png"
if not os.path.exists(img_path):
    print("final_check_100_sec.png not found!")
    exit(1)

img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, bin_inv = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)

h, w = img.shape[:2]

row_sums = np.sum(bin_inv[:, :1000], axis=1) / 255.0
staff_rows = np.where(row_sums > 1000 * 0.4)[0]
if len(staff_rows) < 6:
    print("Cannot find staff lines")
    exit(1)
staff_y_top = staff_rows[0]
staff_y_bottom = staff_rows[-1]

expected_h = staff_y_bottom - staff_y_top
print(f"Staff height: {expected_h}px (from Y={staff_y_top} to {staff_y_bottom})")

col_sums = np.sum(bin_inv[staff_y_top:staff_y_bottom, :], axis=0) / 255.0
bar_xs = np.where(col_sums >= expected_h * 0.6)[0]

grouped_bars = []
if len(bar_xs) > 0:
    curr = [bar_xs[0]]
    for x in bar_xs[1:]:
        if x - curr[-1] < 10: curr.append(x)
        else:
            grouped_bars.append(int(np.mean(curr)))
            curr = [x]
    grouped_bars.append(int(np.mean(curr)))

diffs = np.diff(grouped_bars)
print(f"Total measures: {len(grouped_bars) - 1}")

def get_stats(arr):
    if not len(arr): return "N/A"
    return f"Min: {np.min(arr)}, Max: {np.max(arr)}, Mean: {np.mean(arr):.1f}"

print("Measure width stats:", get_stats(diffs))

anomalies = [i for i, d in enumerate(diffs) if d < 180 or d > 1200]
if anomalies:
    print(f"\n[FAIL] ANOMALIES DETECTED! Mangled measures at indices: {anomalies}")
    for i in anomalies[:20]:
        print(f"  Measure {i}: width {diffs[i]}px (Starts at X={grouped_bars[i]})")
else:
    print("\n[SUCCESS] NO ANOMALIES. All measures have consistent beat widths. No overlapping mangles detected!")
