#!/usr/bin/env python3
"""检测槽位线是否超出板框 / 边缘是否完整
用法: python3 checkleak.py <png> <x0> <y0> <x1> <y1>   # 框矩形(CSS px,来自 cdpsnap 的 geo)
"""
import sys
from PIL import Image

png = sys.argv[1]
x0, y0, x1, y1 = [float(v) for v in sys.argv[2:6]]
SUSER = float(sys.argv[6]) if len(sys.argv)>6 else 0
im = Image.open(png).convert("RGB")
W, H = im.size
S = SUSER if SUSER else W / 390.0
bx0, by0, bx1, by1 = round(x0*S), round(y0*S), round(x1*S), round(y1*S)
px = im.load()

def is_line(r, g, b):
    """焦糖线(≈203,150,92)或深棕(101,43,28)——排除米色纸底与浅点纹"""
    if abs(r-203)<42 and abs(g-150)<38 and abs(b-92)<42 and r>g>b: return True   # 焦糖
    if r<130 and g<80 and b<70 and r>=g>=b: return True                          # 深棕
    return False

# 1) 板框外 3~90 CSS px 环带内是否有线色像素(排除 box-shadow: 右下 7px 偏移的浅影)
margin = 3*S
band = 90*S
hits = []
for y in range(max(0, round(by0-band)), min(H, round(by1+band))):
    for x in range(max(0, round(bx0-band)), min(W, round(bx1+band))):
        if bx0-margin <= x <= bx1+margin and by0-margin <= y <= by1+margin:
            continue  # 板内及贴边跳过
        r, g, b = px[x, y]
        if is_line(r, g, b):
            hits.append((x, y, (r, g, b)))
print(f"board rect in shot: ({bx0},{by0})-({bx1},{by1}), shot {W}x{H}")
print(f"outside-band line-pixels: {len(hits)}")
if hits:
    xs = [h[0] for h in hits]; ys = [h[1] for h in hits]
    print("  x range:", min(xs), max(xs), " y range:", min(ys), max(ys))
    # 聚类粗报:按相对板边的方位分桶
    right = [h for h in hits if h[0] > bx1+margin]
    left  = [h for h in hits if h[0] < bx0-margin]
    below = [h for h in hits if h[1] > by1+margin and bx0<=h[0]<=bx1]
    above = [h for h in hits if h[1] < by0-margin and bx0<=h[0]<=bx1]
    for name, bucket in (("right", right), ("left", left), ("below", below), ("above", above)):
        if bucket:
            bx = [h[0] for h in bucket]; by = [h[1] for h in bucket]
            ext = (max(bx)-bx1) if name=="right" else (bx0-min(bx)) if name=="left" else (max(by)-by1) if name=="below" else (by0-min(by))
            print(f"  {name}: {len(bucket)} px, max extent {ext}px shot = {ext/S:.1f} css px; sample {bucket[:3]}")

# 2) 板内边缘间隙:沿底边内侧 0..6 css px 行,统计每列是否有线色(轮廓是否顶到边框)
def row_profile(edge, side):
    import collections
    has = 0; tot = 0
    if side == "bottom":
        y = by1 - round(margin) - 1
        for x in range(bx0+6, bx1-6):
            tot += 1
            found = any(is_line(*px[x, yy]) for yy in range(y-round(2*S), y+1))
            has += found
    print(f"inner strip along {side}: {has}/{tot} columns have line pixels")

# 3) 裁出关键区域小图供人工/模型查看
crops = {
    "crop_bottom":  (bx0-20, by1-round(40*S), bx1+20, by1+round(40*S)),
    "crop_right":   (bx1-round(40*S), by0-20, bx1+round(40*S), by1+20),
    "crop_br":      (bx1-round(120*S), by1-round(120*S), min(W,bx1+round(40*S)), min(H,by1+round(40*S))),
}
for name, (a, b, c, d) in crops.items():
    im.crop((max(0,a), max(0,b), max(0,c), max(0,d))).save(f"/home/user/shots/{name}_{png.split('/')[-1]}")
print("crops saved")
