import fitz
import cv2
import numpy as np
import os

pdf_path = "output/shintakarajima_perfect.pdf"
if not os.path.exists(pdf_path):
    print("PDF not found!")
    exit(1)

doc = fitz.open(pdf_path)
total_measures = 0
measure_widths = []

print("Running Rigorous Visual Validation against PDF...")

for page_num in range(len(doc)):
    page = doc.load_page(page_num)
    pix = page.get_pixmap(dpi=150)
    img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n)
    if img.shape[2] == 4:
        img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
    elif img.shape[2] == 1:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    _, bin_inv = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY_INV)
    
    row_sums = np.sum(bin_inv, axis=1) / 255.0
    staff_rows = np.where(row_sums > bin_inv.shape[1] * 0.4)[0]
    
    if len(staff_rows) == 0: continue
    
    staves = []
    curr = [staff_rows[0]]
    for y in staff_rows[1:]:
        if y - curr[-1] < 100: curr.append(y)
        else:
            staves.append((curr[0], curr[-1]))
            curr = [y]
    staves.append((curr[0], curr[-1]))
    
    page_measures = 0
    for i, (top, bottom) in enumerate(staves):
        top = max(0, top - 20)
        bottom = min(img.shape[0], bottom + 20)
        
        staff_region = bin_inv[top:bottom, :]
        col_sums = np.sum(staff_region, axis=0) / 255.0
        
        expected_h = bottom - top
        bar_xs = np.where(col_sums >= expected_h * 0.5)[0]
        
        grouped_bars = []
        if len(bar_xs) > 0:
            c = [bar_xs[0]]
            for x in bar_xs[1:]:
                if x - c[-1] < 10: c.append(x)
                else:
                    grouped_bars.append(int(np.mean(c)))
                    c = [x]
            grouped_bars.append(int(np.mean(c)))
            
        if len(grouped_bars) > 1:
            diffs = np.diff(grouped_bars)
            for d in diffs:
                if d > 120: # filter out double bars ||
                    measure_widths.append(d)
                    page_measures += 1
                    total_measures += 1
                    
    print(f"Page {page_num+1:02d}: Extracted {page_measures} measures.")

print("\n--- Absolute Verdict ---")
print(f"Total True Measures Counted: {total_measures}")
if measure_widths:
    print(f"Minimum Width: {np.min(measure_widths):.1f} px")
    print(f"Maximum Width: {np.max(measure_widths):.1f} px")
    print(f"Average Width: {np.mean(measure_widths):.1f} px")
    
    anomalies = [i for i, w in enumerate(measure_widths) if w > 1200 or w < 150]
    if anomalies:
        print(f"FAILED: Found {len(anomalies)} structural anomalies (broken or fused measures)!")
    else:
        print("PASS: 100% of measures have perfectly valid, biologically possible widths. No mangled Frankesteins.")
else:
    print("FAILED: No measures found!")
