"""将指定目录中宽度超过750px的图片缩放到750px宽
用法: python3 resize_images.py <目录路径>
"""
import os, sys, subprocess, re

if len(sys.argv) < 2:
    print("用法: python3 resize_images.py <目录路径>")
    sys.exit(1)

img_dir = sys.argv[1].rstrip('/')
if not os.path.isdir(img_dir):
    print("❌ 目录不存在: %s" % img_dir)
    sys.exit(1)

print("处理目录: %s\n" % img_dir)
resized = 0
skipped = 0

for fname in sorted(os.listdir(img_dir)):
    if not fname.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
        continue
    fpath = os.path.join(img_dir, fname)
    
    result = subprocess.run(['ffmpeg', '-i', fpath], capture_output=True, text=True, timeout=10)
    m = re.search(r'(\d+)x(\d+)', result.stderr)
    if not m:
        skipped += 1
        continue
    
    w, h = int(m.group(1)), int(m.group(2))
    if w <= 750:
        skipped += 1
        continue
    
    new_h = int(h * 750 / w)
    ext = fname.rsplit('.', 1)[1]
    temp_path = fpath + '.tmp.' + ext
    
    subprocess.run(['ffmpeg', '-y', '-i', fpath, '-vf', 'scale=%d:%d' % (750, new_h), temp_path],
                   capture_output=True, timeout=30)
    
    if os.path.exists(temp_path):
        os.replace(temp_path, fpath)
        resized += 1
        print('✅ %s: %dx%d → 750x%d' % (fname, w, h, new_h))

print('\n完成: %d 张已缩放, %d 张无需处理' % (resized, skipped))
