import shutil
import cv2
import subprocess
from pathlib import Path

src = Path(r"C:\Users\Admin\Downloads\media-generation-shot-mo-dam-tien-ngoai-canh-0-c5668077-927b-451c-a45f-6af237cdd0c0.mp4")
dst = Path(r"C:\Projects\KieuStory\04_Assets\videos\ep01_scene05_shot07_10s_v1.mp4")
kf_dir = Path(r"C:\Projects\KieuStory\04_Assets\keyframes\ep01_scene05_shot07")
kf_dir.mkdir(parents=True, exist_ok=True)
kf_out = kf_dir / "clean_frame_239.jpg"

if src.exists():
    shutil.copy2(str(src), str(dst))
    print(f"Copied to: {dst} ({dst.stat().st_size} bytes)")
    
    cap = cv2.VideoCapture(str(dst))
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    print(f"Video Info: {w}x{h} @ {fps:.2f}fps, total frames: {total_frames}")
    
    # Extract last frame
    cap.set(cv2.CAP_PROP_POS_FRAMES, max(0, total_frames - 1))
    ret, frame = cap.read()
    if ret:
        cv2.imwrite(str(kf_out), frame, [cv2.IMWRITE_JPEG_QUALITY, 95])
        print(f"Tail frame saved to: {kf_out}")
    cap.release()
    
    # Verify FFprobe audio
    probe_cmd = f'ffprobe -v error -select_streams a:0 -show_entries stream=codec_name,channels,sample_rate -of default=noprint_wrappers=1 "{dst}"'
    res = subprocess.run(probe_cmd, shell=True, capture_output=True, text=True)
    print(f"Audio probe:\n{res.stdout.strip()}")
else:
    print("Source file not found!")
