# organize_thumbnails.py (fixed)
import os
import hashlib
import shutil

OLD_THUMB_DIR = "static/thumbnails"
HASHED_DIR = "static/thumbnails_hashed"

def hashed_path(video_id: str) -> str:
    """Return hashed path based on video ID (no extension)."""
    h = hashlib.md5(video_id.encode()).hexdigest()
    sub1, sub2 = h[:2], h[2:4]
    return os.path.join(HASHED_DIR, sub1, sub2, f"{video_id}.webp")

def organize_thumbnails():
    os.makedirs(HASHED_DIR, exist_ok=True)
    moved_count = 0

    for root, _, files in os.walk(OLD_THUMB_DIR):
        for file in files:
            video_id = os.path.splitext(file)[0]  # strip extension
            src_path = os.path.join(root, file)
            dest_path = hashed_path(video_id)

            os.makedirs(os.path.dirname(dest_path), exist_ok=True)

            if not os.path.exists(dest_path):
                shutil.move(src_path, dest_path)
                moved_count += 1
            else:
                print(f"[SKIP] Exists: {dest_path}")

    print(f"\n✅ Done! Organized {moved_count} thumbnails into hashed structure.")

if __name__ == "__main__":
    organize_thumbnails()