import cv2
from video_cv_tracker import TemporalTracker
from youtube_tab_to_pdf import extract_unique_scroll, generate_long_image, generate_pdf, download_video, extract_frames
import sys
import os
from pathlib import Path

# Run verification specifically on Shintakarajima
url = "https://youtu.be/tJq1n8TofM0"
video_path = Path("output/サカナクション／新宝島(エレキギターTAB) 難易度★★★ sakanaction shintakarajima.mp4")

print("Extracting full video for final 142-measure verification...")
cap = cv2.VideoCapture(str(video_path))

# PRE-CALCULATE Dynamic Crop
# Just like extract_unique_scroll does automatically, we detect the white band.
ret, initial = cap.read()
scale = 1280 / initial.shape[1]
resized_init = cv2.resize(initial, (1280, int(initial.shape[0] * scale)))

from youtube_tab_to_pdf import _find_white_tab_strip
crop_top = 0
crop_bottom = resized_init.shape[0]

cap.set(cv2.CAP_PROP_POS_FRAMES, 500)
ret, check_frame = cap.read()
if ret:
    resized_check = cv2.resize(check_frame, (1280, int(check_frame.shape[0] * scale)))
    bounds = _find_white_tab_strip(resized_check)
    if bounds:
        crop_top, crop_bottom = bounds
        # Preserve D.S. al Coda, ┌─ 1., ┌─ 2., and measure numbers drawn in the black abyss!
        crop_top = max(0, crop_top - 60)
        
print(f"Dynamically Cropping to: Y={crop_top} to {crop_bottom}")

cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
frames = []
idx = 0
tracker = TemporalTracker(diff_threshold=0.05)

while True:
    ret, frame = cap.read()
    if not ret: break
    
    frame_resized = cv2.resize(frame, (1280, int(frame.shape[0] * scale)))
    clean_ribbon = frame_resized[crop_top:crop_bottom, :]
    frames.append(clean_ribbon)
    idx += 1

cap.release()

cv2.imwrite("C:/Users/Certes/.gemini/antigravity/brain/975cea00-dd68-4689-9ee3-f1a2408b4ee6/raw_frame_check.png", frames[30])

print(f"Extracted {len(frames)} frames. Running sequential page extraction...")
try:
    final_chunks = extract_unique_scroll(frames)
    print("DEBUG: final_chunks len =", len(final_chunks))
    if final_chunks:
        print("DEBUG: final_chunks[0].shape =", final_chunks[0].shape)
        cv2.imwrite("C:/Users/Certes/.gemini/antigravity/brain/975cea00-dd68-4689-9ee3-f1a2408b4ee6/debug_chunk_0.png", final_chunks[0])
    
    # Save the chunks to artifact directory to literally look at it
    artifact_path = Path(os.environ.get('APPDATA', '')) / '..' / 'Local' / 'Google' / 'AndroidStudio2024.1' # Just using relative artifact manually? No, I'll save it to C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6\
    artifact_path = Path(r"C:\Users\Certes\.gemini\antigravity\brain\975cea00-dd68-4689-9ee3-f1a2408b4ee6")
    output_png = artifact_path / "final_check_100_sec.png"
    
    generate_long_image(final_chunks, output_png)
    print(f"Saved successful verification image to: {output_png}")

    if final_chunks:
        generate_pdf(final_chunks, Path("output/shintakarajima_perfect.pdf"))
        print("✨ Successfully generated output/shintakarajima_perfect.pdf ✨")
    else:
        print("Failed to produce rows.")
except Exception as e:
    import traceback
    traceback.print_exc()
