#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最终清理 v2：四角朱红印章区求并集矩形，一次性用外围纸色覆盖。
v3 clean_marks 误伤衣褶（白色方块）；本版只碰纯纸面的印章矩形，深色衣褶一律不动。
"""
import os, hashlib, json
import numpy as np
import cv2
from PIL import Image

WORK = os.path.join(os.path.dirname(os.path.abspath(__file__)), "_s72_work")
PAIRS = [
    ("_e_norm.png", "ep03_s72_monk_cand1_front.png"),
    ("_K_norm.png", "ep03_s72_monk_cand2_front.png"),
]


def sha(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for c in iter(lambda: f.read(1 << 20), b""):
            h.update(c)
    return h.hexdigest()


def clean(src, dst):
    a = np.asarray(Image.open(src).convert("RGB")).astype(np.float32)
    h, w = a.shape[:2]
    a2 = a.copy()
    r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2]
    seal = (r > g + 45) & (r > b + 45) & (r > 95) & (g < 160)
    corner = np.zeros((h, w), bool)
    corner[:int(h * .28), :int(w * .26)] = True
    corner[:int(h * .28), int(w * .74):] = True
    corner[int(h * .70):, :int(w * .26)] = True
    corner[int(h * .70):, int(w * .74):] = True
    m0 = (seal & corner).astype(np.uint8)
    n, lab, stats, _ = cv2.connectedComponentsWithStats(m0, 8)
    # 按四角分组，每组印章像素求外包矩形
    groups = {}
    for i in range(1, n):
        x, y, bw, bh, area = stats[i]
        if area < 4 or area > 4000:
            continue
        cx, cy = x + bw / 2, y + bh / 2
        key = ("L" if cx < w / 2 else "R") + ("T" if cy < h / 2 else "B")
        groups.setdefault(key, []).append((x, y, bw, bh, int(area)))
    rects = []
    for key, items in groups.items():
        x0 = min(it[0] for it in items) - 6
        y0 = min(it[1] for it in items) - 6
        x1 = max(it[0] + it[2] for it in items) + 6
        y1 = max(it[1] + it[3] for it in items) + 6
        x0, y0 = max(0, x0), max(0, y0)
        x1, y1 = min(w, x1), min(h, y1)
        # 只接受小矩形（印章/题款），过大说明是误检，跳过
        if (x1 - x0) > int(w * .16) or (y1 - y0) > int(h * .12):
            continue
        rects.append((key, [int(x0), int(y0), int(x1), int(y1)], sum(it[4] for it in items)))
    for key, (x0, y0, x1, y1), area in rects:
        ring = np.concatenate([
            a2[max(0, y0 - 8):y0, x0:x1].reshape(-1, 3),
            a2[y1:min(h, y1 + 8), x0:x1].reshape(-1, 3),
            a2[y0:y1, max(0, x0 - 8):x0].reshape(-1, 3),
            a2[y0:y1, x1:min(w, x1 + 8)].reshape(-1, 3),
        ], axis=0)
        br = ring[ring.mean(axis=1) > 185]
        paper = np.median(br if len(br) > 20 else ring, axis=0)
        m = np.ones((y1 - y0, x1 - x0), np.float32)
        m[:3, :] *= .5; m[-3:, :] *= .5; m[:, :3] *= .5; m[:, -3:] *= .5
        m = np.clip(m, 0, 1)[:, :, None]
        p = a2[y0:y1, x0:x1]
        a2[y0:y1, x0:x1] = p * (1 - m) + paper[None, None, :] * m
    Image.fromarray(np.clip(a2, 0, 255).astype(np.uint8)).save(dst, "PNG", optimize=True)
    return rects


def audit(src, dst):
    a = np.asarray(Image.open(dst).convert("RGB")).astype(np.float32)
    b = np.asarray(Image.open(src).convert("RGB")).astype(np.float32)
    h, w = a.shape[:2]
    r, g, bl = a[:, :, 0], a[:, :, 1], a[:, :, 2]
    seal = (r > g + 45) & (r > bl + 45) & (r > 95) & (g < 160)
    corner = np.zeros((h, w), bool)
    corner[:int(h * .28), :int(w * .26)] = True
    corner[:int(h * .28), int(w * .74):] = True
    corner[int(h * .70):, :int(w * .26)] = True
    corner[int(h * .70):, int(w * .74):] = True
    diff = (np.abs(a - b).max(axis=2) > 6)
    ys, xs = np.where(diff)
    center = int(((xs > w * .26) & (xs < w * .74) & (ys > h * .28) & (ys < h * .70)).sum()) if len(xs) else 0
    edge = np.concatenate([a[:int(h * .03)].reshape(-1, 3), a[int(h * .97):].reshape(-1, 3)])
    return {"size": [w, h], "ratio": round(w / h, 6),
            "corner_seal_px_left": int((seal & corner).sum()),
            "clean_diff_px": int(diff.sum()),
            "clean_diff_in_center_px": center,
            "paper_rgb": [float(x) for x in np.median(edge, axis=0).round(1)],
            "bytes": os.path.getsize(dst), "sha256": sha(dst)}


def main():
    out = {}
    for src, dst in PAIRS:
        s, d = os.path.join(WORK, src), os.path.join(WORK, dst)
        rects = clean(s, d)
        au = audit(s, d)
        out[dst] = {"seal_rects": rects, **au}
        print(dst, "rects", rects)
        print(json.dumps(au, ensure_ascii=False))
    with open(os.path.join(WORK, "final_audit.json"), "w", encoding="utf-8") as f:
        json.dump(out, f, ensure_ascii=False, indent=2)
    print("OK")


if __name__ == "__main__":
    main()
