import cv2
import numpy as np
import sys
from pathlib import Path

# Load tracker directly to inspect ORB
sys.path.append(str(Path(".").resolve()))
from video_cv_tracker import TemporalTracker

def main():
    print("Testing ORB matcher...")
    # Load test frames from video 1
    cap = cv2.VideoCapture("output/サカナクション／新宝島(エレキギターTAB) 難易度★★★ sakanaction shintakarajima.mp4")
    
    # Fast forward to transition frame
    cap.set(cv2.CAP_PROP_POS_FRAMES, 500)
    
    succ, prev = cap.read()
    curr = prev.copy()
    
    # We will just write a snippet from the actual video loop and manually feed it
    # We can use debug_video1.py ? No, I'll extract real frames directly where the cut happens
    
    # A faster way: Just scan the video for transitions and print the ORB histogram
    tracker = TemporalTracker()
    frame_idx = 500
    transitions_found = 0
    while True:
        succ, frame = cap.read()
        if not succ: break
        if frame_idx % 100 == 0:
            print(f"Reading frame {frame_idx}...", flush=True)
        
        # We need the strip, like youtube_tab_to_pdf.py does
        strip = frame[111:390] # Approximate Region
        
        dx, conf = tracker._calculate_pixel_shift(tracker.last_clean_frame if tracker.last_clean_frame is not None else strip, strip)
        
        if tracker.panorama is None:
            tracker.panorama = strip.copy()
            tracker.last_clean_frame = strip.copy()
            frame_idx += 1
            continue
            
        if (conf < 0.45) or (tracker.last_conf - conf > 0.3):
            tracker.in_transition = True
            
        elif tracker.in_transition and conf > 0.85 and dx == 0:
            tracker.in_transition = False
            print(f"[{frame_idx}] Transition Recovered! Testing ORB...")
            
            # RUN ORB
            search_w = min(1500, tracker.panorama.shape[1])
            search_region = tracker._extract_print_channel(tracker.panorama[:, -search_w:])
            head = tracker._extract_print_channel(strip)
            
            orb = cv2.ORB_create(1000)
            kp1, des1 = orb.detectAndCompute(search_region, None)
            kp2, des2 = orb.detectAndCompute(head, None)
            
            print(f"  kp1: {len(kp1) if kp1 else 0}, kp2: {len(kp2) if kp2 else 0}")
            
            if des1 is not None and des2 is not None and len(des1) > 10 and len(des2) > 10:
                bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)
                matches = bf.match(des1, des2)
                
                dx_votes = []
                for m in matches:
                    x1, y1 = kp1[m.queryIdx].pt
                    x2, y2 = kp2[m.trainIdx].pt
                    if abs(y1 - y2) < 10:
                        dx_votes.append(x1 - x2)
                
                if dx_votes:
                    hist, bins = np.histogram(dx_votes, bins=np.arange(min(dx_votes)-5, max(dx_votes)+5, 5))
                    best_bin_idx = np.argmax(hist)
                    print(f"  Max Vote Count: {hist[best_bin_idx]} at dx={bins[best_bin_idx]}")
                    if hist[best_bin_idx] < 12:
                        print("  => FAILED! Overlap not found (too few ORB matches). Will append complete new page.")
                    else:
                        print("  => SUCCESS! Overlap found.")
                else:
                    print("  => FAILED! No dx votes.")
            else:
                 print("  => FAILED! des1 or des2 is None or less than 10!")
            
            tracker.panorama = np.hstack([tracker.panorama, strip])
            transitions_found += 1
            if transitions_found > 0:
                break
                
        elif dx > 0 and not tracker.in_transition:
            tracker.panorama = np.hstack([tracker.panorama, strip[:, strip.shape[1] - int(dx):, :]])
            
        tracker.last_conf = conf
        tracker.last_clean_frame = strip.copy()
        frame_idx += 1
        
    cap.release()

if __name__ == '__main__':
    main()
