#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
快速压缩脚本 - 专门解决上传照片文件太大问题
自动压缩超过3MB的JPG照片到小于3MB
"""

import os
from PIL import Image

def quick_compress_for_upload(file_path, max_size_mb=3):
    """
    快速压缩图片，专门用于解决上传问题
    
    Args:
        file_path: 图片文件路径
        max_size_mb: 最大文件大小(MB)
    
    Returns:
        bool: 是否成功压缩
    """
    try:
        # 检查文件大小
        original_size = os.path.getsize(file_path)
        original_size_mb = original_size / (1024 * 1024)
        
        print(f"处理文件: {os.path.basename(file_path)}")
        print(f"原始大小: {original_size_mb:.2f}MB")
        
        # 如果文件已经小于目标大小，直接返回
        if original_size_mb <= max_size_mb:
            print(f"✓ 文件已小于{max_size_mb}MB，无需压缩")
            return True
        
        # 打开图片
        with Image.open(file_path) as img:
            # 转换为RGB模式
            if img.mode != 'RGB':
                img = img.convert('RGB')
            
            width, height = img.size
            
            # 如果图片尺寸很大，先调整尺寸
            if max(width, height) > 2000:
                scale = 2000 / max(width, height)
                new_width = int(width * scale)
                new_height = int(height * scale)
                img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
                print(f"调整尺寸至: {new_width}x{new_height}")
            
            # 快速压缩算法
            for quality in [85, 75, 65, 55, 45, 35, 25]:
                temp_file = f"{file_path}.temp"
                img.save(temp_file, format='JPEG', quality=quality, optimize=True)
                
                compressed_size = os.path.getsize(temp_file)
                compressed_size_mb = compressed_size / (1024 * 1024)
                
                print(f"质量{quality}%: {compressed_size_mb:.2f}MB")
                
                if compressed_size_mb <= max_size_mb:
                    # 成功压缩，替换原文件
                    os.replace(temp_file, file_path)
                    compression_ratio = (original_size - compressed_size) / original_size * 100
                    print(f"✓ 压缩成功！质量:{quality}%, 压缩率:{compression_ratio:.1f}%")
                    return True
                else:
                    os.remove(temp_file)
            
            print("✗ 无法压缩到目标大小")
            return False
            
    except Exception as e:
        print(f"✗ 压缩失败: {str(e)}")
        return False

def compress_student_photos():
    """
    压缩学生照片目录中的所有照片
    """
    students_dir = "./students/"
    
    if not os.path.exists(students_dir):
        print(f"目录不存在: {students_dir}")
        return
    
    print("开始压缩学生照片...")
    print("=" * 40)
    
    success_count = 0
    failed_count = 0
    skipped_count = 0
    
    # 获取所有JPG文件
    jpg_files = []
    for root, dirs, files in os.walk(students_dir):
        for file in files:
            if file.lower().endswith(('.jpg', '.jpeg')):
                jpg_files.append(os.path.join(root, file))
    
    print(f"找到 {len(jpg_files)} 张照片")
    print("-" * 40)
    
    # 处理每张照片
    for i, file_path in enumerate(jpg_files, 1):
        print(f"\n[{i}/{len(jpg_files)}] {os.path.basename(file_path)}")
        
        # 快速压缩
        if quick_compress_for_upload(file_path, max_size_mb=3):
            success_count += 1
        else:
            failed_count += 1
    
    # 统计结果
    print("\n" + "=" * 40)
    print("压缩完成！")
    print(f"成功: {success_count}")
    print(f"失败: {failed_count}")
    print(f"总计: {len(jpg_files)}")

def compress_single_photo(file_path):
    """
    压缩单张照片
    """
    if not os.path.exists(file_path):
        print(f"文件不存在: {file_path}")
        return
    
    if not file_path.lower().endswith(('.jpg', '.jpeg')):
        print(f"不是JPG格式文件: {file_path}")
        return
    
    print(f"压缩单张照片: {os.path.basename(file_path)}")
    print("-" * 30)
    
    quick_compress_for_upload(file_path, max_size_mb=3)

if __name__ == "__main__":
    import sys
    
    print("快速照片压缩工具")
    print("=" * 30)
    print("专门解决上传照片文件太大问题")
    print()
    
    if len(sys.argv) > 1:
        # 命令行模式
        file_path = sys.argv[1]
        if os.path.exists(file_path):
            if os.path.isfile(file_path):
                compress_single_photo(file_path)
            elif os.path.isdir(file_path):
                # 如果是目录，切换到该目录并压缩
                original_dir = os.getcwd()
                os.chdir(file_path)
                compress_student_photos()
                os.chdir(original_dir)
        else:
            print(f"路径不存在: {file_path}")
    else:
        # 交互模式
        print("选择操作:")
        print("1. 压缩学生照片目录")
        print("2. 压缩单张照片")
        print("3. 自定义目录")
        
        choice = input("\n请输入选择(1-3): ").strip()
        
        if choice == "1":
            compress_student_photos()
        elif choice == "2":
            file_path = input("请输入照片文件路径: ").strip()
            compress_single_photo(file_path)
        elif choice == "3":
            dir_path = input("请输入目录路径: ").strip()
            if os.path.exists(dir_path):
                original_dir = os.getcwd()
                os.chdir(dir_path)
                compress_student_photos()
                os.chdir(original_dir)
            else:
                print(f"目录不存在: {dir_path}")
        else:
            print("无效选择")