import cv2
import numpy as np
import time
import glob
from video_cv_tracker import TemporalTracker
from score_extractor import ScoreExtractor

def test_pipeline():
    videos = glob.glob('output/*.mp4')
    if not videos: return
    cap = cv2.VideoCapture(videos[0])
    
    # 1. Tracker extracts median jump-cut pages flawlessly
    tracker = TemporalTracker(diff_threshold=0.05)
    
    # Process 100 seconds
    limit_frames = 3000
    
    count = 0
    t0 = time.time()
    while count < limit_frames:
        ret, frame = cap.read()
        if not ret: break
        
        # We only pass the lower tab bounding box if needed.
        # But actually, finding the tab strip directly using robust median is safer.
        # Let's just crop roughly the bottom 2/3rds where tab lives, reducing processing load.
        h = frame.shape[0]
        roi = frame[int(h*0.3):h, :]
        
        tracker.process_frame(roi)
        count += 1
        if count % 300 == 0:
            print(f"Processed {count} frames...")
            
    cap.release()
    unique_pages = tracker.get_unique_pages()
    print(f"Tracker returned {len(unique_pages)} unique structural median pages. Took {time.time()-t0:.2f}s")
    
    # 2. Score Extractor applies the Ultimate Structure State Machine
    t1 = time.time()
    extractor = ScoreExtractor()
    extractor.process_pages(unique_pages)
    tiled_rows = extractor.tile_to_a4(chunk_width=1280)
    print(f"Extraction & Tiling took {time.time()-t1:.2f}s")
    
    if tiled_rows:
        final_img = np.vstack(tiled_rows)
        # Invert back to black-on-white PDF format
        pdf_img = cv2.bitwise_not(final_img)
        cv2.imwrite("C:/Users/Certes/Desktop/guitar_score/debug_final_state_machine.png", pdf_img)
        print("Wrote debug_final_state_machine.png")
    else:
        print("Failed to produce rows.")

if __name__ == "__main__":
    test_pipeline()
