#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""04 静态图初检：拼总览图 + 采样上下纸色差 + 墨迹下缘。"""
import glob, os, sys
import numpy as np
from PIL import Image, ImageDraw, ImageFont

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

RAW = r"D:/WorkBuddyProd/chili04/imgs_raw"
HERE = r"D:/Download/muse_exchange"
files = sorted(glob.glob(os.path.join(RAW, "*.png")))
print("count=%d" % len(files))

TW, TH = 270, 472
sheet = Image.new("RGB", (TW * 4, (TH + 26) * 2), (235, 231, 222))
try:
    font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 18)
except Exception:
    font = ImageFont.load_default()

for idx, f in enumerate(files):
    im = Image.open(f).convert("RGB")
    a = np.asarray(im, dtype=np.float32)
    h, w = a.shape[:2]
    # 上/下纸色采样（取左右边缘避开主体）
    edge = np.concatenate([a[20:int(h * .12), 10:90].reshape(-1, 3),
                           a[20:int(h * .12), w - 90:w - 10].reshape(-1, 3)], axis=0)
    top = edge.mean(axis=0)
    bot = a[int(h * .90):h - 10, :, :].reshape(-1, 3).mean(axis=0)
    # 墨迹下缘（离上部纸色远的像素，按行计数）
    dist = np.abs(a - top).sum(axis=2)
    ink = dist > 120
    rows = np.where(ink.sum(axis=1) >= 8)[0]
    inkbot = int(rows.max()) if len(rows) else 0
    print("%d %-58s size=%s top=%s bot=%s delta=%s inkbot=%d (%.1f%%)" %
          (idx + 1, os.path.basename(f)[:58], im.size,
           tuple(int(v) for v in top), tuple(int(v) for v in bot),
           tuple(int(v) for v in (bot - top)), inkbot, 100.0 * inkbot / h))
    thumb = im.resize((TW, TH), Image.LANCZOS)
    x, y = (idx % 4) * TW, (idx // 4) * (TH + 26)
    sheet.paste(thumb, (x, y))
    ImageDraw.Draw(sheet).text((x + 6, y + TH + 3), "%02d %s" % (idx + 1, os.path.basename(f)[-14:-4]),
                              fill=(30, 30, 30), font=font)

out = os.path.join(HERE, "chili04_contact_sheet.png")
sheet.save(out)
print("sheet ->", out)
