from pathlib import Path
from PIL import Image

root = Path(__file__).resolve().parent.parent
exts = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.tiff']

files = []
for ext in exts:
    files.extend(root.rglob(f'*{ext}'))

files = [p for p in files if p.is_file() and p.stat().st_size > 500 * 1024]
files = sorted(set(files), key=lambda p: p.stat().st_size, reverse=True)
print('Large image files found:', len(files))

if not files:
    print('No large image files found.')
    raise SystemExit(0)

for p in files:
    out = p.with_suffix('.webp')
    if out.exists() and out.stat().st_mtime >= p.stat().st_mtime:
        print('SKIP', p.relative_to(root), 'already converted')
        continue

    try:
        with Image.open(p) as img:
            if img.mode not in ('RGB', 'RGBA'):
                img = img.convert('RGBA' if 'A' in img.getbands() else 'RGB')
            img.save(out, 'WEBP', quality=80)
        print('CONVERTED', p.relative_to(root), '->', out.relative_to(root), 'size=', out.stat().st_size)
    except Exception as exc:
        print('ERROR', p.relative_to(root), exc)
