# -*- coding: utf-8 -*-
"""
扫描所有下载的图片，找出损坏/截断的文件，删除并重置数据库状态以便重新下载
运行环境：VPS6（图片存储服务器）
"""
import os
import sys
import re

sys.path.append(os.path.dirname(sys.path[0]))
from PIL import Image
import PIL
from all_connect import ConnectSpider

PIL.Image.MAX_IMAGE_PIXELS = 933120000
Con = ConnectSpider()

all_pic_dir = "/home/wangjing/picture_material/stock_summery/all_pic"


def verify_image(file_path):
    """验证图片是否完整，返回True=正常，False=损坏"""
    try:
        with Image.open(file_path) as img:
            img.verify()
        with Image.open(file_path) as img:
            img.load()
        return True
    except Exception as e:
        print(f"损坏文件: {file_path} | 原因: {e}")
        return False


def scan_and_clean():
    image_extensions = ['.jpg', '.jpeg', '.png']
    bad_files = []
    total = 0

    for account_folder in os.listdir(all_pic_dir):
        folder_path = os.path.join(all_pic_dir, account_folder)
        if not os.path.isdir(folder_path):
            continue

        for file_name in os.listdir(folder_path):
            if not any(file_name.lower().endswith(ext) for ext in image_extensions):
                continue

            total += 1
            file_path = os.path.join(folder_path, file_name)

            if os.path.getsize(file_path) == 0:
                print(f"空文件: {file_path}")
                bad_files.append((file_path, file_name))
                continue

            if not verify_image(file_path):
                bad_files.append((file_path, file_name))

    print(f"\n===== 扫描完成 =====")
    print(f"总计扫描: {total} 张")
    print(f"损坏文件: {len(bad_files)} 张")

    if not bad_files:
        print("没有损坏文件，无需处理")
        return

    bad_image_ids = []
    for file_path, file_name in bad_files:
        match = re.match(r"^(\d+)\+", file_name)
        if match:
            image_id = match.group(1)
            bad_image_ids.append(image_id)

        os.remove(file_path)
        print(f"已删除: {file_path}")

    if bad_image_ids:
        print(f"\n需要处理 {len(bad_image_ids)} 条记录")
        for image_id in bad_image_ids:
            try:
                with Con.db_engine192.begin() as conn:
                    conn.execute(f"DELETE FROM stock_image_detail_wj WHERE image_id = '{image_id}'")
                    conn.execute(f"UPDATE stock_image_id_wj SET state = 1 WHERE image_id = '{image_id}' AND state = 3")
                    print(f"已处理 image_id: {image_id} | detail已删除, id表state已重置")
            except Exception as e:
                print(f"处理 {image_id} 失败: {e}")

    print(f"\n===== 处理完成 =====")
    print(f"已删除 {len(bad_files)} 个损坏文件")
    print(f"已处理 {len(bad_image_ids)} 条数据库记录")
    print(f"先运行 xnj_url.py 获取新URL，再运行 download_pic.py 下载")


if __name__ == '__main__':
    scan_and_clean()
