"""
损坏图片清理工具（旧版）
功能与 clean_bad_pics.py 类似，扫描并清理损坏的图片文件
"""
import os
import re
from PIL import Image
from all_connect import ConnectSpider

Con = ConnectSpider()
all_pic_dir = "/home/wangjing/picture_material/stock_summery/all_pic"

bad_files = []

print('===== 第一步：扫描坏文件 =====')
for account_dir in os.listdir(all_pic_dir):
    account_path = os.path.join(all_pic_dir, account_dir)
    if not os.path.isdir(account_path):
        continue
    for file_name in os.listdir(account_path):
        file_path = os.path.join(account_path, file_name)
        if not os.path.isfile(file_path):
            continue
        if not file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
            continue
        try:
            with Image.open(file_path) as img:
                img.verify()
        except Exception:
            image_id_list = re.findall(r"^(\d+)\+", file_name)
            image_id = image_id_list[0] if image_id_list else None
            bad_files.append((image_id, file_path))
            print(f'坏文件: image_id={image_id}  {file_path}')

print(f'\n共发现 {len(bad_files)} 个坏文件')

if not bad_files:
    print('没有坏文件，退出')
    exit()

print('\n===== 第二步：删除坏文件 + 重置DB状态为1 =====')
success_count = 0
fail_count = 0
for image_id, file_path in bad_files:
    try:
        os.remove(file_path)
        if image_id:
            with Con.db_engine192.begin() as conn:
                conn.execute(f"UPDATE stock_image_detail_wj SET state = 1 WHERE image_id = '{image_id}'")
            print(f'已处理: image_id={image_id}')
        else:
            print(f'已删除非标准命名坏文件（不更新DB）: {file_path}')
        success_count += 1
    except Exception as e:
        print(f'处理失败 image_id={image_id}: {e}')
        fail_count += 1

print(f'\n===== 清理完成：成功 {success_count} 个，失败 {fail_count} 个 =====')
