#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
image_stats.py —— 图像信息统计：确定性算出图片的客观量化指标。

为什么需要这个脚本？
====================
minimal-agent 内核已支持多模态读图，模型能「看懂」图片；但「看懂」≠「量化」。
宽高 / 分辨率 / 平均颜色 / 色调 / 直方图这类**具体数字**靠模型目测既不准也不稳——
它会凭印象说「偏暖、大概 1920×1080」，却说不出平均 RGB、主色占比、亮度方差。
这些都是确定性计算，应交脚本（与 image_plan_lint.py / layout_balance.py /
deck_pages_check.py 同哲学：机械活收归脚本，不烧 LLM、零幻觉）。

算什么？
========
对每张图片：
  - 基本：format / mode / 文件大小 / 是否带 alpha
  - 尺寸：width×height / 宽高比 / 朝向(landscape/portrait/square) / 百万像素
  - 分辨率：DPI（无元数据则 null）
  - 平均颜色：平均 RGB + hex + 逐通道
  - 亮度/对比：感知亮度均值 / 标准差(≈对比度) / min / max
  - 色调：HSV 的饱和度加权环形平均 hue + 平均 sat/val + warm/cool/neutral 分类 + 是否灰阶
  - 主色：quantize 取 top-N 主色 + 各自 hex 与占比
  - 直方图：R/G/B 三通道 + 亮度，默认 16 bin 分箱（--bins 256 出全直方图）

只依赖 Pillow + 标准库（json/argparse/os/sys/math）——**不引入 numpy**
（全仓库未用；PIL 自带 histogram()/ImageStat/quantize()/convert('HSV') 已够）。

诚实边界
========
- 逐像素统计（色调/主色/直方图）前把分析副本缩略到最长边 ≤512px 提速；
  尺寸/DPI/format 仍报**原图**真实值，不受缩略影响。
- 平均色/色调基于 RGB 通道，**忽略 alpha**（透明像素的 RGB 也计入）；带 alpha 的图另有 has_alpha 标注。
- 色调环形平均按饱和度加权（避免大片灰色噪声拉偏 hue）；饱和度极低时判 grayscale、hue 记 null。
- warm/cool/neutral 是色环的粗分类启发式（见 classify_tone），不是色彩学严格定义。

退出码：0 = 正常（至少统计到 1 张，或 --scan 未发现图片）；1 = 指定了图片但一张都读不了；2 = 参数错。
单张图片读失败 → 打到 stderr 跳过、不影响其余。

用法
====
    python image_stats.py a.png b.jpg              # 文本报告
    python image_stats.py ./shots --scan           # 扫目录下所有受支持图片（非递归）
    python image_stats.py a.png --json             # 机读 JSON（工作流/宿主消费，stdout 只有 JSON）
    python image_stats.py a.png --bins 256 --top 8 # 全直方图 + 取 8 个主色
"""

import argparse
import json
import math
import os
import sys

from PIL import Image, ImageStat

# --scan 扫目录时识别的图片后缀；直接传文件路径则不受此限、能开就统计。
SUPPORTED_EXT = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tif", ".tiff"}

# 逐像素统计前缩略到的最长边像素（仅为提速，不改原图、不影响尺寸/DPI 报告）。
ANALYSIS_MAX_SIDE = 512

# 朝向阈值：与 extract_source_assets.py 保持一致，避免两套脚本对同一图判断打架。
LANDSCAPE_MIN = 1.25
PORTRAIT_MAX = 0.80

# 判定灰阶的平均饱和度上限（0~1）。低于此视为基本无彩色。
GRAYSCALE_SAT_MAX = 0.08


def human_size(n: int) -> str:
    """字节数 → 人话（B/KB/MB）。"""
    f = float(n)
    for unit in ("B", "KB", "MB", "GB"):
        if f < 1024 or unit == "GB":
            return f"{f:.0f} {unit}" if unit == "B" else f"{f:.1f} {unit}"
        f /= 1024
    return f"{f:.1f} GB"


def to_hex(rgb) -> str:
    r, g, b = (int(round(c)) for c in rgb[:3])
    return f"#{r:02X}{g:02X}{b:02X}"


def classify_orientation(ar: float) -> str:
    if ar >= LANDSCAPE_MIN:
        return "landscape"
    if ar <= PORTRAIT_MAX:
        return "portrait"
    return "square"


def classify_tone(hue_deg, is_grayscale: bool) -> str:
    """色环粗分类（启发式）：grayscale / warm / cool / neutral。"""
    if is_grayscale or hue_deg is None:
        return "grayscale"
    h = hue_deg % 360
    if h < 45 or h >= 315:
        return "warm"  # 红/橙 与 品红→红
    if 90 <= h < 270:
        return "cool"  # 绿/青/蓝/紫
    return "neutral"  # 黄(45~90) 与 紫红(270~315) 过渡带


def bin_histogram(counts, bins: int):
    """把 256 桶的单通道直方图重分箱到 bins 个桶。"""
    if bins >= 256:
        return list(counts)
    out = [0] * bins
    width = 256.0 / bins
    for i, c in enumerate(counts):
        out[min(bins - 1, int(i / width))] += c
    return out


def compute_tone(hsv: Image.Image):
    """对 HSV 缩略图算「饱和度加权环形平均 hue」+ 平均 sat/val。

    线性平均 hue 会因为红色在 0°/360° 处回绕而出错；这里用 sin/cos 向量和做环形
    平均，并以饱和度为权重（灰色像素 hue 无意义、不该参与）。
    """
    sin_sum = 0.0
    cos_sum = 0.0
    sat_weight = 0.0
    sat_total = 0.0
    val_total = 0.0
    n = 0
    for h, s, v in iter_pixels(hsv):  # PIL HSV：每通道 0~255
        n += 1
        sat_total += s
        val_total += v
        if s > 0:
            ang = (h / 256.0) * 2 * math.pi
            sin_sum += math.sin(ang) * s
            cos_sum += math.cos(ang) * s
            sat_weight += s
    if n == 0:
        return {"hue_deg": None, "saturation": 0.0, "value": 0.0}
    sat_mean = (sat_total / n) / 255.0
    val_mean = (val_total / n) / 255.0
    if sat_weight > 0 and (sin_sum or cos_sum):
        hue_deg = math.degrees(math.atan2(sin_sum, cos_sum)) % 360.0
    else:
        hue_deg = None
    return {
        "hue_deg": None if hue_deg is None else round(hue_deg, 1),
        "saturation": round(sat_mean, 4),
        "value": round(val_mean, 4),
    }


def iter_pixels(image: Image.Image):
    """兼容 Pillow 新旧版本的像素迭代。

    Pillow 13 起 Image.getdata() 弃用；新版提供 get_flattened_data()。这里优先用
    新 API，旧环境 fallback，避免为了一个像素迭代引入 numpy。
    """
    getter = getattr(image, "get_flattened_data", None)
    if callable(getter):
        return getter()
    return image.getdata()


def dominant_colors(rgb: Image.Image, top: int):
    """quantize 取 top-N 主色（含占比）。颜色数不足时自然返回更少。"""
    q = rgb.quantize(colors=max(1, top), method=Image.Quantize.MEDIANCUT)
    palette = q.getpalette() or []
    counts = q.getcolors() or []  # [(count, palette_index), ...]
    total = sum(c for c, _ in counts) or 1
    counts.sort(reverse=True)
    out = []
    for count, idx in counts[:top]:
        r, g, b = palette[idx * 3 : idx * 3 + 3]
        out.append(
            {"hex": to_hex((r, g, b)), "rgb": [r, g, b], "ratio": round(count / total, 4)}
        )
    return out


def analyze(path: str, bins: int, top: int) -> dict:
    """统计单张图片，返回机读 dict。读失败抛异常由调用方捕获。"""
    file_size = os.path.getsize(path)
    with Image.open(path) as img:
        fmt = img.format
        mode = img.mode
        width, height = img.size
        dpi = img.info.get("dpi")
        has_alpha = (
            mode in ("RGBA", "LA", "PA")
            or (mode == "P" and "transparency" in img.info)
            or "transparency" in img.info
        )

        # 逐像素统计用的缩略 RGB 副本（thumbnail 只缩不放、保宽高比）。
        rgb = img.convert("RGB")

    analysis = rgb.copy()
    analysis.thumbnail((ANALYSIS_MAX_SIDE, ANALYSIS_MAX_SIDE))

    # 平均颜色 + 逐通道
    rstat = ImageStat.Stat(analysis)
    avg = rstat.mean  # [r, g, b]

    # 感知亮度（PIL 的 'L' 用 ITU-R 601-2：0.299R+0.587G+0.114B，正是感知亮度）
    lum = analysis.convert("L")
    lstat = ImageStat.Stat(lum)
    lo, hi = lstat.extrema[0]

    # 色调
    tone = compute_tone(analysis.convert("HSV"))
    is_gray = mode in ("L", "1", "I", "F") or tone["saturation"] < GRAYSCALE_SAT_MAX
    category = classify_tone(tone["hue_deg"], is_gray)

    # 直方图（分箱）
    rgb_hist = analysis.histogram()  # 768：R[0:256] G[256:512] B[512:768]
    hist = {
        "bins": bins if bins < 256 else 256,
        "r": bin_histogram(rgb_hist[0:256], bins),
        "g": bin_histogram(rgb_hist[256:512], bins),
        "b": bin_histogram(rgb_hist[512:768], bins),
        "luminance": bin_histogram(lum.histogram(), bins),
    }

    ar = width / height if height else 0.0
    return {
        "path": path,
        "format": fmt,
        "mode": mode,
        "file_size_bytes": file_size,
        "file_size_human": human_size(file_size),
        "has_alpha": bool(has_alpha),
        "width": width,
        "height": height,
        "aspect_ratio": round(ar, 4),
        "orientation": classify_orientation(ar),
        "megapixels": round(width * height / 1_000_000, 2),
        "dpi": list(dpi) if dpi else None,
        "average_color": {
            "rgb": [round(c, 1) for c in avg],
            "hex": to_hex(avg),
        },
        "brightness": {
            "mean": round(lstat.mean[0], 1),
            "stddev": round(lstat.stddev[0], 1),
            "min": lo,
            "max": hi,
        },
        "tone": {
            "hue_deg": tone["hue_deg"],
            "saturation": tone["saturation"],
            "value": tone["value"],
            "category": category,
            "is_grayscale": bool(is_gray),
        },
        "dominant_colors": dominant_colors(analysis, top),
        "histogram": hist,
    }


def _spark(counts) -> str:
    """把分箱直方图渲染成一行迷你火花线（仅文本报告用）。"""
    blocks = "▁▂▃▄▅▆▇█"
    peak = max(counts) if counts else 0
    if peak == 0:
        return " " * len(counts)
    return "".join(blocks[min(7, int(c / peak * 7))] for c in counts)


def render_text(s: dict) -> str:
    """单张图片的人话报告。"""
    L = []
    L.append(f"📷 {s['path']}")
    L.append(
        f"   格式 {s['format']} / {s['mode']}"
        f"{' / 含透明' if s['has_alpha'] else ''}   大小 {s['file_size_human']}"
    )
    dpi = f"   DPI {s['dpi'][0]:g}×{s['dpi'][1]:g}" if s["dpi"] else ""
    L.append(
        f"   尺寸 {s['width']}×{s['height']}px"
        f"（{s['orientation']}，比例 {s['aspect_ratio']}，{s['megapixels']}MP）{dpi}"
    )
    ac = s["average_color"]
    L.append(f"   平均色 {ac['hex']} rgb{tuple(ac['rgb'])}")
    b = s["brightness"]
    L.append(
        f"   亮度 均值 {b['mean']}/255  对比(σ) {b['stddev']}  范围 {b['min']}~{b['max']}"
    )
    t = s["tone"]
    hue = "n/a" if t["hue_deg"] is None else f"{t['hue_deg']}°"
    L.append(
        f"   色调 {t['category']}  hue {hue}  饱和 {t['saturation']}  明度 {t['value']}"
    )
    doms = "  ".join(f"{d['hex']}({d['ratio'] * 100:.0f}%)" for d in s["dominant_colors"])
    L.append(f"   主色 {doms}")
    h = s["histogram"]
    L.append(f"   直方图({h['bins']}bin)  L {_spark(h['luminance'])}")
    L.append(
        f"               R {_spark(h['r'])}  G {_spark(h['g'])}  B {_spark(h['b'])}"
    )
    return "\n".join(L)


def collect_targets(args) -> list:
    """把位置参数解析成图片路径列表（--scan 时把目录展开为受支持图片）。"""
    targets = []
    for t in args.targets:
        if args.scan and os.path.isdir(t):
            for name in sorted(os.listdir(t)):
                if os.path.splitext(name)[1].lower() in SUPPORTED_EXT:
                    targets.append(os.path.join(t, name))
        else:
            targets.append(t)
    return targets


def main() -> int:
    # 强制 UTF-8 输出：脚本含中文，Windows 默认 GBK 控制台/管道会乱码或崩溃，
    # 宿主（minimal-agent Bash 工具已 chcp 65001）按 UTF-8 捕获才稳。
    for stream in (sys.stdout, sys.stderr):
        try:
            stream.reconfigure(encoding="utf-8")
        except Exception:
            pass

    parser = argparse.ArgumentParser(
        description="图像信息统计（确定性）：宽高/分辨率/平均色/色调/主色/直方图"
    )
    parser.add_argument("targets", nargs="+", help="图片路径（可多个）；配 --scan 则为目录")
    parser.add_argument("--scan", action="store_true", help="把目录参数展开为其中所有受支持图片（非递归）")
    parser.add_argument("--json", action="store_true", help="输出机读 JSON 数组（stdout 只有 JSON）")
    parser.add_argument("--bins", type=int, default=16, help="直方图分箱数（默认 16；256 = 全直方图）")
    parser.add_argument("--top", type=int, default=5, help="主色个数（默认 5）")
    parser.add_argument("-v", "--verbose", action="store_true", help="把每张图进度打到 stderr")
    args = parser.parse_args()

    if args.bins < 1 or args.bins > 256:
        print("参数错误：--bins 必须在 1~256 之间", file=sys.stderr)
        return 2
    if args.top < 1:
        print("参数错误：--top 必须 >= 1", file=sys.stderr)
        return 2

    targets = collect_targets(args)
    results = []
    for path in targets:
        if args.verbose:
            print(f"[image-stats] 统计 {path}", file=sys.stderr)
        try:
            results.append(analyze(path, args.bins, args.top))
        except Exception as e:  # 单张失败不影响其余
            print(f"[image-stats] 跳过 {path}：{e}", file=sys.stderr)

    marker = f"IMAGE_STATS: 统计 {len(results)} 张图片（共 {len(targets)} 个目标）"
    if args.json:
        print(json.dumps(results, ensure_ascii=False, indent=2))
        print(marker, file=sys.stderr)  # JSON 模式 stdout 保持纯净，marker 走 stderr
    else:
        print("\n\n".join(render_text(s) for s in results) if results else "（无可统计图片）")
        print("\n" + marker)

    # 指定了目标却一张都没读出来 → 视为失败，让宿主/调用者能察觉。
    if targets and not results:
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
