#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""validate.py — 校验出图完整性（PNG 可解码、非截断、非重复），并列出需要重出的项。

用法: python3 validate.py [目录...]   # 默认校验 01-04 四个目录（含可爱版）
输出: 损坏/重复清单；退出码 1 表示有问题
"""
import hashlib, os, sys
from PIL import Image

DIRS = sys.argv[1:] or ["01-风格测试", "02-人物设定", "03-妖怪设定", "04-场景设定",
                        "01-风格测试-可爱版", "02-人物设定-可爱版", "03-妖怪设定-可爱版", "04-场景设定-可爱版"]

bad, hashes, dup = [], {}, []
for d in DIRS:
    if not os.path.isdir(d):
        continue
    for fn in sorted(os.listdir(d)):
        if not fn.lower().endswith((".png", ".jpg")) or fn.startswith("_"):
            continue
        p = os.path.join(d, fn)
        try:
            im = Image.open(p); im.load()
            if min(im.size) < 512:
                bad.append((p, f"尺寸异常 {im.size}"))
        except Exception as e:
            bad.append((p, f"损坏: {e}"))
            continue
        h = hashlib.md5(open(p, "rb").read()).hexdigest()
        if h in hashes:
            dup.append((p, hashes[h]))
        else:
            hashes[h] = p

print(f"检查完成：文件 {len(hashes) + len(dup)} 个")
if bad:
    print("\n[损坏/异常]")
    for p, r in bad:
        print(" ", p, "→", r)
if dup:
    print("\n[重复]")
    for p, q in dup:
        print(" ", p, "== ", q)
if not bad and not dup:
    print("全部正常 ✓")
sys.exit(1 if (bad or dup) else 0)
