"""小红书图片快速评分器 v3 — 封面/内页区分 + 智能阈值"""
import json, sys
import numpy as np
from PIL import Image

ORANGE = np.array([230, 126, 34])
DARK = np.array([40, 90, 55])
GREEN_MID = np.array([100, 155, 115])
GREEN_TINT = np.array([220, 238, 210])

def analyze_image(path, is_cover=False):
    img = Image.open(path).convert("RGB")
    img = img.resize((img.width // 4, img.height // 4), Image.LANCZOS)
    arr = np.array(img, dtype=np.float32)
    h, w = arr.shape[:2]
    gray = np.mean(arr, axis=2)
    non_white = np.sum(gray < 240)
    density = non_white / (w * h) * 100
    
    scores = {}
    details = {}
    
    # 1. 元素完整性
    dark_px = np.sum(np.sqrt(np.sum((arr[:20,:,:] - DARK)**2, axis=2)) < 50)
    has_bar = dark_px > w * 8
    has_footer = np.mean(arr[h-20:h,:,:]) < 200
    dark_title = np.sum(np.sqrt(np.sum((arr[25:50,:,:] - DARK)**2, axis=2)) < 60)
    has_title = dark_title > 200
    
    es = 20
    if not is_cover:
        if not has_bar: es -= 7
        if not has_footer: es -= 7
        if not has_title: es -= 6
    scores['元素完整性'] = max(0, es)
    
    # 2. 排版密度
    if is_cover:
        tz = gray[70:130, :]
        td = np.sum(tz < 240) / (tz.shape[0]*tz.shape[1]) * 100
        ds = 20 if td > 5 else 15
    else:
        if 15 <= density <= 35: ds = 20
        elif 10 <= density < 15 or 35 < density <= 45: ds = 15
        elif 5 <= density < 10 or 45 < density <= 55: ds = 10
        else: ds = 5
    scores['排版密度'] = ds
    details['text_density'] = round(density, 1)
    
    # 3. 对齐精度
    lc = np.sum(gray[30:, :25] < 240)
    rc = np.sum(gray[30:, w-25:w] < 240)
    ms = 1 - abs(lc - rc) / max(lc + rc, 1)
    mid = np.sum(gray[:, w//2-12:w//2+12] < 200) / (h * 25)
    details['margin_symmetry'] = round(ms, 2)
    details['center_density'] = round(mid, 3)
    
    as_ = 20
    if ms < 0.7: as_ -= 6
    if ms < 0.5: as_ -= 6
    if not is_cover and mid < 0.05: as_ -= 4
    if lc > rc * 3 or rc > lc * 3: as_ -= 5
    scores['对齐精度'] = max(0, as_)
    
    # 4. 色彩节奏
    opx = int(np.sum(np.sqrt(np.sum((arr - ORANGE)**2, axis=2)) < 50))
    dpx = int(np.sum(np.sqrt(np.sum((arr - DARK)**2, axis=2)) < 50))
    tpx = int(np.sum(np.sqrt(np.sum((arr - GREEN_TINT)**2, axis=2)) < 40))
    details['orange_px'] = opx
    details['dark_px'] = dpx
    details['tint_px'] = tpx
    
    cs = 20
    if not is_cover:
        if opx < 25: cs -= 8
        elif opx < 100: cs -= 4
        if dpx < 100: cs -= 5
        if tpx < 400: cs -= 4
    else:
        if opx < 100: cs -= 5
        if dpx < 1000: cs -= 5
    scores['色彩节奏'] = max(0, cs)
    
    # 5. 无重叠
    rnw = np.sum(gray < 240, axis=1) / w
    ol = int(np.sum(rnw > 0.65))
    gaps = 0; gc = 0
    for r in rnw:
        if r < 0.02: gc += 1
        else:
            if gc > 20: gaps += 1
            gc = 0
    details['overload_rows'] = ol
    details['blank_gaps'] = gaps
    
    os_ = 20
    if is_cover:
        if ol > 50: os_ -= 10
    else:
        if ol > 15: os_ -= 10
        elif ol > 8: os_ -= 6
        elif ol > 3: os_ -= 3
    if gaps > 4: os_ -= 5
    if gaps > 2: os_ -= 3
    scores['无重叠'] = max(0, os_)
    
    total = sum(scores.values())
    return {"file": path, "dimensions": f"{img.width*4}x{img.height*4}", "scores": scores, "details": details, "total": total}


if __name__ == "__main__":
    results = []
    for p in sys.argv[1:]:
        try:
            is_cov = "cover" in p.lower()
            r = analyze_image(p, is_cover=is_cov)
            results.append(r)
        except Exception as e:
            results.append({"file": p, "error": str(e)})
    
    for r in results:
        if "error" in r:
            print(f"\n❌ {r['file']}: {r['error']}")
        else:
            print(f"\n📊 {r['file']} ({r['dimensions']})")
            print(f"   总分: {r['total']}/100")
            for dim, score in r['scores'].items():
                bar = "█" * (score // 2) + "░" * (10 - score // 2)
                print(f"   {dim}: {score}/20  {bar}")
            print(f"   {json.dumps(r['details'], ensure_ascii=False)}")
    
    valid = [r for r in results if "error" not in r]
    if valid:
        avg = sum(r['total'] for r in valid) / len(valid)
        print(f"\n📈 平均分: {avg:.1f}/100")
        below = [r for r in valid if r['total'] < 90]
        if below:
            print(f"⚠️ 未达90分: {len(below)}/{len(valid)} 张")
            for r in below:
                weak = [k for k, v in r['scores'].items() if v < 17]
                print(f"   {r['file']}: {r['total']}分 弱项={weak}")
