import sys

with open('youtube_tab_to_pdf.py', 'r', encoding='utf-8') as f:
    lines = f.readlines()

new_lines = []
skip = False

import_added = False

for line in lines:
    if line.startswith('import cv2') and not import_added:
        new_lines.append(line)
        new_lines.append('from video_cv_tracker import TemporalTracker\n')
        import_added = True
        continue
        
    if line.startswith('def extract_unique_scroll(frames:'):
        skip = True
        new_lines.append('''def extract_unique_scroll(frames: List[np.ndarray], threshold: float = SIMILARITY_THRESHOLD) -> List[np.ndarray]:
    print(f"[4/5] 스크롤형 Tab 시계열 추적 추출 중...")
    
    strip_tops, strip_bottoms = [], []
    for frame in frames[:50]:
        strip = _find_white_tab_strip(frame)
        if strip:
            strip_tops.append(strip[0])
            strip_bottoms.append(strip[1])
            
    if not strip_tops:
        return []
        
    median_top = int(np.median(strip_tops))
    median_bottom = int(np.median(strip_bottoms))
    
    tracker = TemporalTracker()
    
    for frame in frames:
        h = frame.shape[0]
        tab_crop = frame[max(0, median_top):min(h, median_bottom), :]
        if not _has_tab_content(tab_crop): 
            continue
        tracker.process_frame(tab_crop)

    panorama = tracker.get_final_panorama()
    if panorama is None:
        return []
        
    print(f"  -> 생성된 파노라마 길이: {panorama.shape[1]}px")
    
    chunk_width = 1280
    final_chunks = []
    
    w = panorama.shape[1]
    start_x = 0
    
    while start_x < w:
        chunk = panorama[:, start_x:min(w, start_x + chunk_width)]
        if chunk.shape[1] < chunk_width:
            pad = np.full((chunk.shape[0], chunk_width - chunk.shape[1], 3), 255, dtype=np.uint8)
            chunk = np.hstack([chunk, pad])
        final_chunks.append(chunk)
        start_x += chunk_width
        
    print(f"  -> A4 분할 컷: {len(final_chunks)}개")
    return final_chunks

''')
        continue
        
    if skip and line.startswith('def extract_unique_overlay('):
        skip = False

    if not skip:
        new_lines.append(line)

with open('youtube_tab_to_pdf.py', 'w', encoding='utf-8') as f:
    f.writelines(new_lines)
    
print("Patched youtube_tab_to_pdf.py successfully.")
