#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""D45 构建脚本：读取输入图，计算哈希/差异，分组，生成数据与页面。

用法（在 outputs/ 下）：
    python3 tools/analyze.py
    python3 tools/analyze.py --bmv-max 40 --ssim-min 0.93
    python3 tools/analyze.py --check          # 额外做验收比对并打印表格

输入只读：本脚本只以 "rb" 打开 inputs/images/*.png；所有写入都在 outputs/ 内。
依赖：仅 CPython 标准库（见 README「复现」）。
"""

import argparse
import csv
import itertools
import json
import math
import os
import shutil
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
OUT_ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)

import imgcore as ic  # noqa: E402

TOOL_NAME = "d45-image-dedup"
TOOL_VERSION = "1.0.0"

DEFAULTS = {
    "bmv_max": 24,
    "ahash_max": 4,
    "dhash_max": 4,
    "ssim_min": 0.90,
    "phash_max": None,
    "tol": 8,
}


# --------------------------------------------------------------------------- #
# 小工具
# --------------------------------------------------------------------------- #
def rnd(x, nd=4):
    return round(float(x), nd)


def pct(x, nd=2):
    return ("%." + str(nd) + "f%%") % x


def file_sha(path):
    return ic.sha256_file(path)


def partition(groups):
    return frozenset(frozenset(g) for g in groups)


def relation_pairs(groups):
    out = set()
    for g in groups:
        for a, b in itertools.combinations(sorted(g), 2):
            out.add((a, b))
    return out


def delta_text(base_groups, other_groups):
    """对比两种分组：返回 (被拆开的关系, 被合并的关系) 的简短描述。"""
    base = relation_pairs(base_groups)
    other = relation_pairs(other_groups)
    return ([a + " ↔ " + b for a, b in sorted(base - other)],
            [a + " ↔ " + b for a, b in sorted(other - base)])


def write_csv(path, header, rows):
    # utf-8-sig 让 Excel 正确识别中文；字段名保持 ASCII 便于程序读取
    with open(path, "w", encoding="utf-8-sig", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(header)
        for row in rows:
            w.writerow(row)


def write_json(path, obj):
    with open(path, "w", encoding="utf-8") as fh:
        json.dump(obj, fh, ensure_ascii=False, indent=2, sort_keys=False)
        fh.write("\n")


def to_hex_bits(hexstr):
    return bin(int(hexstr, 16)).count("1")


def hamming_hex(h1, h2):
    return bin(int(h1, 16) ^ int(h2, 16)).count("1")


# --------------------------------------------------------------------------- #
# 度量
# --------------------------------------------------------------------------- #
def load_images(input_dir):
    names = sorted(n for n in os.listdir(input_dir) if n.lower().endswith(".png"))
    imgs = {}
    for name in names:
        path = os.path.join(input_dir, name)
        w, h, rgb = ic.read_png(path)
        gray = ic.to_gray(w, h, rgb)
        npx = w * h
        uniq = set()
        sr = sg = sb = 0
        for i in range(0, len(rgb), 3):
            px = (rgb[i], rgb[i + 1], rgb[i + 2])
            uniq.add(px)
            sr += px[0]
            sg += px[1]
            sb += px[2]
        imgs[name] = {
            "name": name,
            "bytes": os.path.getsize(path),
            "width": w,
            "height": h,
            "sha256": file_sha(path),
            "pixel_sha256": ic.pixel_digest(w, h, rgb),
            "ahash": ic.bits_to_hex(ic.ahash(gray, w, h)),
            "dhash": ic.bits_to_hex(ic.dhash(gray, w, h)),
            "phash": ic.bits_to_hex(ic.phash(gray, w, h)),
            "bmvhash": ic.bits_to_hex(ic.bmvbhash(gray, w, h, 16)),
            "unique_colors": len(uniq),
            "mean_rgb": [rnd(sr / npx, 2), rnd(sg / npx, 2), rnd(sb / npx, 2)],
            "_rgb": rgb,
            "_gray": gray,
        }
    return names, imgs


def aligned_stats(rgb_a, rgb_b, w, h, ox, oy, tol):
    """把 B 平移 (ox,oy) 后与 A 逐像素比较；只统计重叠区。"""
    total = 0
    cnt = 0
    mx = 0
    over = 0
    diff_map = bytearray(w * h)
    mask = bytearray(w * h)
    for y in range(h):
        by = y + oy
        for x in range(w):
            bx = x + ox
            if bx < 0 or bx >= w or by < 0 or by >= h:
                continue
            i = 3 * (y * w + x)
            j = 3 * (by * w + bx)
            dr = abs(rgb_a[i] - rgb_b[j])
            dg = abs(rgb_a[i + 1] - rgb_b[j + 1])
            db = abs(rgb_a[i + 2] - rgb_b[j + 2])
            m = max(dr, dg, db)
            diff_map[y * w + x] = m
            mask[y * w + x] = 1
            total += dr + dg + db
            cnt += 3
            if m > mx:
                mx = m
            if m > tol:
                over += 1
    npx = cnt / 3.0
    return {
        "mae": rnd(total / cnt if cnt else 0.0, 6),
        "max_abs": mx,
        "pct_over_tol": rnd(100.0 * over / npx if npx else 0.0, 4),
        "overlap_px": int(npx),
        "diff_map": diff_map,
        "mask": mask,
    }


def is_near(p, th):
    """四道内容门槛（可单独置 None 关闭，仅用于诊断实验）。"""
    for key in ("bmv", "ah", "dh"):
        limit = th.get(key)
        if limit is not None and p[key] > limit:
            return False
    limit = th.get("ssim")
    if limit is not None and p["ssim"] < limit:
        return False
    limit = th.get("phash")
    if limit is not None and p["ph"] > limit:
        return False
    return True


def gate_flags(p, th):
    return {
        "bmv": p["bmv"] <= th["bmv"],
        "ah": p["ah"] <= th["ah"],
        "dh": p["dh"] <= th["dh"],
        "ssim": p["ssim"] >= th["ssim"],
        "phash": None if th.get("phash") is None else (p["ph"] <= th["phash"]),
    }


def derive_examples(res):
    """从分析结果推导报告/页面要引用的具体案例，避免任何硬编码文件名。"""
    names, imgs, pairs = res["names"], res["imgs"], res["pairs"]
    near, singles = res["near_groups"], res["singles"]
    th = res["th"]

    def pair_of(a, b):
        for p in pairs:
            if (p["a"], p["b"]) == (a, b) or (p["b"], p["a"]) == (a, b):
                return p
        raise KeyError((a, b))

    exact_pair = res["exgroups"][0][:2] if res["exgroups"] else None
    groups = []
    for g in near:
        row = next(r for r in res["group_rows"]
                   if r["group_type"] == "near"
                   and set(r["members"].split(";")) == set(g))
        canon = row["canonical"]
        npx = imgs[canon]["width"] * imgs[canon]["height"]
        members = []
        for f in g:
            if f == canon:
                continue
            p = pair_of(canon, f)
            if p["exact_byte"]:
                kind = "exact"
            elif p["uniform_delta"] is not None and p["pct_over_tol"] == 0:
                kind = "uniform"
            elif p["shift"]["offset_x"] or p["shift"]["offset_y"]:
                kind = "shift"
            elif p["pct_over_tol"] <= 1.0:
                kind = "local"
            else:
                kind = "other"
            members.append({
                "file": f,
                "kind": kind,
                "offset": [p["shift"]["offset_x"], p["shift"]["offset_y"]],
                "uniform_delta": p["uniform_delta"],
                "pct": p["pct_over_tol"],
                "pixels": int(round(p["pct_over_tol"] * npx / 100.0)),
                "max_abs": p["max_abs"],
                "mae": p["mae"],
                "aligned_mae": p["aligned"]["mae"],
                "ssim": p["ssim"],
                "bmv": p["bmv"],
                "colors": p.get("_change_colors", []),
            })
        groups.append({"gid": row["group_id"], "canonical": canon, "members": members})

    intra = [pair_of(a, b) for g in near for a, b in itertools.combinations(g, 2)]
    ph_pair = max(intra, key=lambda p: (p["ph"], p["a"])) if intra else None

    ph_chain = None
    for t in range(65):
        only = {k: None for k in ("bmv", "ah", "dh", "ssim", "phash")}
        only["phash"] = t
        g2, _ = classify(names, pairs, only)
        if len(g2) == 1:
            ph_chain = t
            break

    max_shift = 0
    for grp in groups:
        for m in grp["members"]:
            max_shift = max(max_shift, abs(m["offset"][0]), abs(m["offset"][1]))

    min_intra_ssim = min((pair_of(a, b)["ssim"] for g in near
                          for a, b in itertools.combinations(g, 2)), default=None)

    return {
        "exact_pair": exact_pair,
        "groups": groups,
        "ph_pair": [ph_pair["a"], ph_pair["b"]] if ph_pair else None,
        "ph_value": ph_pair["ph"] if ph_pair else None,
        "ph_chain_threshold": ph_chain,
        "max_shift": max_shift,
        "min_intra_ssim": min_intra_ssim,
        "singles": singles,
        "note": "报告与页面只引用这里的名字；没有任何示例文件名是写死的。",
    }


def build_union(files):
    parent = {f: f for f in files}

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    def union(a, b):
        ra, rb = find(a), find(b)
        if ra == rb:
            return
        # 固定按字典序合并，结果与遍历顺序无关
        if ra < rb:
            parent[rb] = ra
        else:
            parent[ra] = rb

    def groups():
        buckets = {}
        for f in files:
            buckets.setdefault(find(f), []).append(f)
        return sorted((sorted(v) for v in buckets.values()), key=lambda g: g[0])

    return find, union, groups


def classify(files, pairs, th):
    find, union, groups = build_union(files)
    verdicts = []
    for p in pairs:
        if p["exact_byte"]:
            v = "same"
        elif is_near(p, th):
            v = "near"
        else:
            v = "distinct"
        verdicts.append(v)
        if v != "distinct":
            union(p["a"], p["b"])
    return groups(), verdicts


def exact_groups(files, pairs):
    find, union, groups = build_union(files)
    for p in pairs:
        if p["exact_byte"]:
            union(p["a"], p["b"])
    return groups()


# --------------------------------------------------------------------------- #
# 差异描述
# --------------------------------------------------------------------------- #
def diff_summary(p):
    """用可复核的数字描述这一对图差在哪。"""
    if p["exact_byte"]:
        return "SHA-256 完全一致（字节级重复）"
    parts = []
    if p["shift"]["offset_x"] or p["shift"]["offset_y"]:
        parts.append("整体平移 (%+d,%+d)px" % (p["shift"]["offset_x"], p["shift"]["offset_y"]))
    if p["uniform_delta"] is not None:
        d = p["uniform_delta"]
        parts.append("全幅均匀色偏 %+d/%+d/%+d（RGB 每通道）" % (d[0], d[1], d[2]))
    if p["pct_over_tol"] > 0:
        parts.append("%s 像素超过 %d 级通道差（最大 %d）"
                     % (pct(p["pct_over_tol"]), p["tol"], p["max_abs"]))
    else:
        parts.append("没有像素超过 %d 级通道差（最大 %d）" % (p["tol"], p["max_abs"]))
    return "；".join(parts)


# --------------------------------------------------------------------------- #
# 构建
# --------------------------------------------------------------------------- #
def build(args):
    out_root = os.path.abspath(args.out)
    inputs = os.path.abspath(args.inputs)
    spec_path = os.path.abspath(args.spec) if args.spec else None

    th = {
        "bmv": args.bmv_max,
        "ah": args.ahash_max,
        "dh": args.dhash_max,
        "ssim": args.ssim_min,
        "phash": args.phash_max,
    }
    tol = args.tol

    names, imgs = load_images(inputs)

    pairs = []
    for a, b in itertools.combinations(names, 2):
        ia, ib = imgs[a], imgs[b]
        if (ia["width"], ia["height"]) != (ib["width"], ib["height"]):
            raise SystemExit("尺寸不同暂不支持逐像素比较: %s / %s" % (a, b))
        w, h = ia["width"], ia["height"]
        pd = ic.pixel_diff(w, h, ia["_rgb"], ib["_rgb"], tol=tol)
        ssim = ic.ssim_block(ia["_gray"], ib["_gray"], w, h)
        sh = ic.best_shift_gray(ia["_gray"], ib["_gray"], w, h, radius=16)
        ox, oy = -sh["dx"], -sh["dy"]
        al = aligned_stats(ia["_rgb"], ib["_rgb"], w, h, ox, oy, tol)
        p = {
            "a": a,
            "b": b,
            "exact_byte": ia["sha256"] == ib["sha256"],
            "pixel_equal": ia["pixel_sha256"] == ib["pixel_sha256"],
            "bmv": hamming_hex(ia["bmvhash"], ib["bmvhash"]),
            "ah": hamming_hex(ia["ahash"], ib["ahash"]),
            "dh": hamming_hex(ia["dhash"], ib["dhash"]),
            "ph": hamming_hex(ia["phash"], ib["phash"]),
            "mae": rnd(pd["mae"], 6),
            "rmse": rnd(pd["rmse"], 6),
            "max_abs": pd["max_abs"],
            "pct_over_tol": rnd(pd["pct_over_tol"], 4),
            "tol": tol,
            "uniform_delta": pd["uniform_delta"],
            "ssim": rnd(ssim, 6),
            "shift": {"offset_x": ox, "offset_y": oy},
            "aligned": {
                "mae": al["mae"],
                "max_abs": al["max_abs"],
                "pct_over_tol": al["pct_over_tol"],
                "overlap_px": al["overlap_px"],
            },
            "_raw_diff": pd["diff_map"],
            "_aligned_diff": al["diff_map"],
            "_aligned_mask": al["mask"],
            "_gain_raw": (255.0 / pd["max_abs"]) if pd["max_abs"] else 0.0,
            "_gain_aligned": (255.0 / al["max_abs"]) if al["max_abs"] else 0.0,
        }
        p["summary"] = diff_summary(p)
        if 0 < p["pct_over_tol"] <= 1.0:
            from collections import Counter
            ca, cb, dm = ia["_rgb"], ib["_rgb"], pd["diff_map"]
            cnt = Counter()
            for i, d in enumerate(dm):
                if d > tol:
                    cnt[(bytes(ca[3 * i:3 * i + 3]).hex(),
                         bytes(cb[3 * i:3 * i + 3]).hex())] += 1
            p["_change_colors"] = [list(k) + [v] for k, v in cnt.most_common(3)]
        pairs.append(p)

    groups, verdicts = classify(names, pairs, th)
    for p, v in zip(pairs, verdicts):
        p["verdict"] = v
        p["gates"] = gate_flags(p, th)

    exgroups = [g for g in exact_groups(names, pairs) if len(g) > 1]
    near_groups = [g for g in groups if len(g) > 1]

    def pair_of(a, b):
        for p in pairs:
            if (p["a"], p["b"]) == (a, b) or (p["b"], p["a"]) == (a, b):
                return p
        raise KeyError((a, b))

    # 单链接分组是否为完全图（组内两两都满足关系）——用于排除链式误并
    clique_violations = []
    for g in near_groups:
        for a, b in itertools.combinations(g, 2):
            pr = pair_of(a, b)
            if not (pr["exact_byte"] or is_near(pr, th)):
                clique_violations.append([a, b])

    # 阈值稳定性：单指标一维扫描，记录分组不变区间
    base_part = partition(groups)
    stable = {}
    sweeps = {
        "bmv": list(range(0, 257)),
        "ah": list(range(0, 65)),
        "dh": list(range(0, 65)),
        "ssim": [round(0.5 + 0.002 * k, 3) for k in range(251)],
    }
    for key, values in sweeps.items():
        ok = []
        for v in values:
            t2 = dict(th)
            t2[key] = v
            g2, _ = classify(names, pairs, t2)
            if partition(g2) == base_part:
                ok.append(v)
        entry = {"lo": ok[0] if ok else None, "hi": ok[-1] if ok else None,
                 "count": len(ok), "grid": [values[0], values[-1], len(values)]}
        if ok:
            i_lo = values.index(ok[0])
            i_hi = values.index(ok[-1])
            entry["contiguous"] = (i_hi - i_lo + 1) == len(ok)
            if i_lo > 0:
                g2, _ = classify(names, pairs, dict(th, **{key: values[i_lo - 1]}))
                s, m = delta_text(groups, g2)
                entry["below"] = {"value": values[i_lo - 1], "split": s, "merge": m}
            if i_hi + 1 < len(values):
                g2, _ = classify(names, pairs, dict(th, **{key: values[i_hi + 1]}))
                s, m = delta_text(groups, g2)
                entry["above"] = {"value": values[i_hi + 1], "split": s, "merge": m}
        stable[key] = entry

    # 单指标独立可用区间：只启用一项门控时，能复现默认分组的阈值范围
    single = {}
    for key, values in list(sweeps.items()) + [("phash", list(range(0, 65)))]:
        ok = []
        for v in values:
            t2 = {k: None for k in ("bmv", "ah", "dh", "ssim", "phash")}
            t2[key] = v
            g2, _ = classify(names, pairs, t2)
            if partition(g2) == base_part:
                ok.append(v)
        single[key] = {"lo": ok[0] if ok else None,
                       "hi": ok[-1] if ok else None,
                       "count": len(ok),
                       "grid": [values[0], values[-1], len(values)]}
        if ok:
            entry = single[key]
            entry["contiguous"] = (values.index(ok[-1]) - values.index(ok[0]) + 1) == len(ok)
            if values.index(ok[0]) > 0:
                g2, _ = classify(names, pairs, {**{k: None for k in ("bmv", "ah", "dh", "ssim", "phash")},
                                                key: values[values.index(ok[0]) - 1]})
                s2, m2 = delta_text(groups, g2)
                entry["below"] = {"value": values[values.index(ok[0]) - 1], "split": s2, "merge": m2}
            if values.index(ok[-1]) + 1 < len(values):
                g2, _ = classify(names, pairs, {**{k: None for k in ("bmv", "ah", "dh", "ssim", "phash")},
                                                key: values[values.index(ok[-1]) + 1]})
                s2, m2 = delta_text(groups, g2)
                entry["above"] = {"value": values[values.index(ok[-1]) + 1], "split": s2, "merge": m2}

    # pHash 单独门控的对照实验（默认不启用）
    ph_demo = None
    if th["phash"] is None:
        t_ph = dict(th)
        t_ph["phash"] = 8
        g_ph, _ = classify(names, pairs, t_ph)
        s, m = delta_text(groups, g_ph)
        ph_demo = {"phash_max": 8, "groups": g_ph, "split": s, "merge": m}

    # 指标余量：同组最大距离 / 异组最小距离
    intra_pairs = [pr for g in near_groups for pr in itertools.combinations(g, 2)]
    in_group = {frozenset(pr) for pr in intra_pairs}
    inter_pairs = [pr for pr in itertools.combinations(names, 2)
                   if frozenset(pr) not in in_group]
    intra_pairs = [(p["a"], p["b"]) for p in pairs
                   if frozenset((p["a"], p["b"])) in {frozenset(x) for x in intra_pairs}]
    inter_pairs = [(p["a"], p["b"]) for p in pairs
                   if frozenset((p["a"], p["b"])) in {frozenset(x) for x in inter_pairs}]

    def margins(key):
        intra = [pair_of(a, b)[key] for a, b in intra_pairs]
        inter = [pair_of(a, b)[key] for a, b in inter_pairs]
        return max(intra), min(inter), min(intra), max(inter)

    m_bmv = margins("bmv")
    m_ah = margins("ah")
    m_dh = margins("dh")
    m_ph = margins("ph")
    m_ssim = margins("ssim")

    metrics_table = {
        "bmv": {"kind": "hamming", "bits": 256,
                "intra_max": m_bmv[0], "inter_min": m_bmv[1], "threshold": th["bmv"]},
        "ah": {"kind": "hamming", "bits": 64,
               "intra_max": m_ah[0], "inter_min": m_ah[1], "threshold": th["ah"]},
        "dh": {"kind": "hamming", "bits": 64,
               "intra_max": m_dh[0], "inter_min": m_dh[1], "threshold": th["dh"]},
        "ph": {"kind": "hamming", "bits": 64, "note": "仅诊断，默认不参与判定",
               "intra_max": m_ph[0], "inter_min": m_ph[1], "threshold": th["phash"]},
        "ssim": {"kind": "similarity", "intra_min": m_ssim[2], "inter_max": m_ssim[3],
                 "intra_max": m_ssim[0], "inter_min": m_ssim[1], "threshold": th["ssim"]},
    }

    # 组编号与保留建议
    group_rows = []
    rec_rows = []
    for i, g in enumerate(exgroups, 1):
        shas = sorted({imgs[f]["sha256"] for f in g})
        group_rows.append({
            "group_id": "EX-%d" % i,
            "group_type": "exact",
            "size": len(g),
            "members": ";".join(g),
            "canonical": g[0],
            "evidence": "SHA-256 %s（%d 个成员字节一致）" % (shas[0], len(g)),
            "min_intra_bmv": 0,
            "max_intra_bmv": 0,
            "min_intra_ssim": 1.0,
            "note": "字节级完全一致，判定不含任何阈值",
        })

    def dist_score(a, b):
        p = pair_of(a, b)
        return p["bmv"] / 256.0 + p["ah"] / 64.0 + p["dh"] / 64.0 + (1.0 - p["ssim"])

    for i, g in enumerate(near_groups, 1):
        gid = "NR-%d" % i
        medoid = min(g, key=lambda f: (sum(dist_score(f, o) for o in g if o != f), f))
        intra_bmv = min(pair_of(a, b)["bmv"] for a, b in itertools.combinations(g, 2))
        intra_bmv_max = max(pair_of(a, b)["bmv"] for a, b in itertools.combinations(g, 2))
        intra_ssim = min(pair_of(a, b)["ssim"] for a, b in itertools.combinations(g, 2))
        group_rows.append({
            "group_id": gid,
            "group_type": "near",
            "size": len(g),
            "members": ";".join(g),
            "canonical": medoid,
            "evidence": ("组内 bmvhash 距离 %d/256" % intra_bmv
                         if intra_bmv == intra_bmv_max else
                         "组内 bmvhash 距离 %d–%d/256" % (intra_bmv, intra_bmv_max))
                        + "；最小 SSIM %.4f" % intra_ssim,
            "min_intra_bmv": intra_bmv,
            "max_intra_bmv": intra_bmv_max,
            "min_intra_ssim": intra_ssim,
            "note": "阈值内近似，不等于绝对相同",
        })
        for f in g:
            ex = next((eg for eg in exgroups if f in eg and medoid in eg), None)
            if f == medoid:
                role, action = "canonical", "keep"
                reason = "组内内容中心（到其他成员的归一化距离和最小），作为该组代表"
            elif ex is not None:
                role, action = "exact_duplicate", "dedupe-after-backup"
                reason = "与 %s 的 SHA-256 完全相同（%s…）" % (medoid, imgs[f]["sha256"][:16])
            else:
                role, action = "variant", "keep-as-variant"
                reason = "与 %s 存在可解释差异：%s" % (medoid, pair_of(medoid, f)["summary"])
            rec_rows.append({
                "file": f, "group_id": gid, "group_type": "near",
                "role": role, "action": action, "reason": reason,
                "backup_required": "yes" if action == "dedupe-after-backup" else "no",
            })

    singles = [f for f in names if not any(f in g for g in near_groups)]
    single_ids = {"S-%d" % (i + 1): f for i, f in enumerate(singles)}
    for sid, f in single_ids.items():
        nearest = min((p for p in pairs if f in (p["a"], p["b"])),
                      key=lambda p: (p["bmv"], -p["ssim"]))
        group_rows.append({
            "group_id": sid, "group_type": "single", "size": 1, "members": f,
            "canonical": f,
            "evidence": "最近邻 %s：bmv %d/256、SSIM %.4f，四项指标未同时过阈值"
                        % (nearest["b"] if nearest["a"] == f else nearest["a"],
                           nearest["bmv"], nearest["ssim"]),
            "min_intra_bmv": None, "max_intra_bmv": None,
            "min_intra_ssim": None, "note": "孤立文件",
        })
        rec_rows.append({
            "file": f, "group_id": sid, "group_type": "single",
            "role": "singleton", "action": "keep",
            "reason": "与其余图片的最近 bmvhash 距离 %d/256、SSIM %.4f，不构成近似"
                      % (nearest["bmv"], nearest["ssim"]),
            "backup_required": "no",
        })

    rec_rows.sort(key=lambda r: (res_order(names).index(r["file"])))

    # 联合放宽实验：把最接近的两个族并成一族至少需要多松（由数据推导）
    cluster_labels = []
    for i, g in enumerate(near_groups):
        cluster_labels.append("NR-%d" % (i + 1))
    for sid in single_ids:
        cluster_labels.append(sid)
    clusters = [list(g) for g in near_groups] + [[f] for f in singles]
    frontier = None
    for i, j in itertools.combinations(range(len(clusters)), 2):
        for a in clusters[i]:
            for b in clusters[j]:
                pr = pair_of(a, b)
                score = (pr["bmv"] / 256.0 + pr["ah"] / 64.0 + pr["dh"] / 64.0
                         + (1.0 - pr["ssim"]))
                if frontier is None or score < frontier[0]:
                    frontier = (score, pr, i, j)
    joint_demo = None
    if frontier:
        _score, fp, ci, cj = frontier
        joint_th = {"bmv": fp["bmv"], "ah": fp["ah"], "dh": fp["dh"],
                    "ssim": math.floor(fp["ssim"] * 10000) / 10000.0, "phash": None}
        g_joint, _ = classify(names, pairs, joint_th)
        strict_th = dict(joint_th, ssim=round(fp["ssim"] + 0.001, 4))
        g_strict, _ = classify(names, pairs, strict_th)
        relax = {}
        for key in ("bmv", "ah", "dh", "ssim"):
            g2, _ = classify(names, pairs, dict(th, **{key: joint_th[key]}))
            relax[key] = partition(g2) == base_part
        joint_demo = {
            "frontier_pair": [fp["a"], fp["b"]],
            "cluster_ids": [cluster_labels[ci], cluster_labels[cj]],
            "thresholds": joint_th,
            "strict_ssim": strict_th["ssim"],
            "groups": g_joint,
            "strict_groups": g_strict,
            "merged": len(g_joint) < len(groups),
            "strict_merged": len(g_strict) < len(groups),
            "single_gate_relax_unchanged": relax,
        }


    # 验收比对（真值只用于验收，不参与判定）
    validation = None
    if spec_path and os.path.exists(spec_path):
        with open(spec_path, "r", encoding="utf-8") as fh:
            spec = json.load(fh)
        got_exact = sorted(tuple(sorted(g)) for g in exgroups)
        want_exact = sorted(tuple(sorted(g)) for g in spec.get("expectedExactGroups", []))
        got_near = sorted(tuple(sorted(g)) for g in near_groups)
        want_near = sorted(tuple(sorted(g)) for g in spec.get("expectedNearFamilies", []))
        validation = {
            "spec": os.path.relpath(spec_path, out_root),
            "exact_match": got_exact == want_exact,
            "near_match": got_near == want_near,
            "got_exact": [list(x) for x in got_exact],
            "want_exact": [list(x) for x in want_exact],
            "got_near": [list(x) for x in got_near],
            "want_near": [list(x) for x in want_near],
            "note": "真值文件仅用于验收；分组过程不读取文件名或真值。",
        }

    examples = derive_examples({
        "names": names, "imgs": imgs, "pairs": pairs,
        "near_groups": near_groups, "singles": singles,
        "exgroups": exgroups, "group_rows": group_rows,
        "single_ids": single_ids, "th": th,
    })

    return {
        "out_root": out_root, "inputs": inputs, "th": th, "tol": tol,
        "examples": examples,
        "names": names, "imgs": imgs, "pairs": pairs,
        "groups": groups, "exgroups": exgroups, "near_groups": near_groups,
        "singles": singles, "single_ids": single_ids,
        "clique_violations": clique_violations, "stable": stable,
        "single": single, "joint_demo": joint_demo,
        "ph_demo": ph_demo, "metrics_table": metrics_table,
        "group_rows": group_rows, "rec_rows": rec_rows,
        "validation": validation,
    }


def rename_experiment(args, res):
    """改名实验：把输入复制成随机文件名后重跑，验证分组不依赖文件名。"""
    import hashlib
    import tempfile

    names = res["names"]
    order = sorted(names, key=lambda n: hashlib.sha256(("d45-rename|" + n).encode()).hexdigest())
    mapping = {}
    tmp = tempfile.mkdtemp(prefix="d45-rename-")
    try:
        for i, n in enumerate(order, 1):
            new = "sample-%02d.png" % i
            mapping[n] = new
            shutil.copy2(os.path.join(res["inputs"], n), os.path.join(tmp, new))
        a2 = argparse.Namespace(**vars(args))
        a2.inputs = tmp
        a2.spec = None
        a2.skip_assets = True
        r2 = build(a2)
    finally:
        shutil.rmtree(tmp, ignore_errors=True)
    back = {v: k for k, v in mapping.items()}
    mapped = sorted(sorted(back[f] for f in g) for g in r2["groups"])
    return {
        "same_structure": mapped == res["groups"],
        "mapping": mapping,
        "renamed_groups": r2["groups"],
        "mapped_back_groups": mapped,
        "original_groups": res["groups"],
        "note": "把 7 张图复制到临时目录并改名为 sample-NN.png 后重跑；分组只依赖像素。",
    }


def res_order(names):
    return names


# --------------------------------------------------------------------------- #
# 资源：原图副本 + 四联对照图
# --------------------------------------------------------------------------- #
def heat(d, gain):
    t = min(1.0, d * gain / 255.0)
    r = int(round(255 * min(1.0, t * 1.8)))
    g = int(round(255 * max(0.0, min(1.0, t * 2.4 - 1.2))))
    b = int(round(255 * max(0.0, t * 0.9 - 0.55)))
    return (r, g, b)


def make_composite(path, ia, ib, raw, aligned, mask, gain_raw, gain_aligned):
    panel = 256
    gap = 12
    W = 4 * panel + 5 * gap
    H = panel + 2 * gap
    canvas = bytearray(bytes((246, 247, 250)) * (W * H))

    def paste(x0, y0, rgb):
        for y in range(panel):
            dst = 3 * ((y0 + y) * W + x0)
            src = 3 * (y * panel)
            canvas[dst:dst + 3 * panel] = rgb[src:src + 3 * panel]

    paste(gap, gap, ia["_rgb"])
    paste(gap * 2 + panel, gap, ib["_rgb"])

    buf = bytearray(panel * panel * 3)
    for i in range(panel * panel):
        r, g, b = heat(raw[i], gain_raw)
        buf[3 * i] = r
        buf[3 * i + 1] = g
        buf[3 * i + 2] = b
    paste(gap * 3 + panel * 2, gap, buf)

    for i in range(panel * panel):
        if mask[i]:
            r, g, b = heat(aligned[i], gain_aligned)
        else:
            r, g, b = (40, 42, 52)
        buf[3 * i] = r
        buf[3 * i + 1] = g
        buf[3 * i + 2] = b
    paste(gap * 4 + panel * 3, gap, buf)
    ic.write_png(path, W, H, canvas)


def write_assets(res, args):
    # 静态前端资源（手写源文件）随构建复制到目标 assets/，保证 --out 到任意目录都可打开
    web_src = os.path.join(HERE, "web")
    web_dst = os.path.join(res["out_root"], "assets")
    os.makedirs(web_dst, exist_ok=True)
    for fn in ("grouping.js", "sandbox.js", "style.css"):
        src = os.path.join(web_src, fn)
        if not os.path.exists(src):
            raise SystemExit("缺少静态资源: %s" % src)
        shutil.copy2(src, os.path.join(web_dst, fn))

    img_dir = os.path.join(res["out_root"], "assets", "images")
    pair_dir = os.path.join(res["out_root"], "assets", "pairs")
    os.makedirs(img_dir, exist_ok=True)
    os.makedirs(pair_dir, exist_ok=True)

    for f in res["names"]:
        src = os.path.join(res["inputs"], f)
        dst = os.path.join(img_dir, f)
        if args.skip_assets and os.path.exists(dst):
            if file_sha(src) != file_sha(dst):
                raise SystemExit("已有副本与输入不一致，拒绝跳过: %s" % f)
            continue
        shutil.copy2(src, dst)
        if file_sha(src) != file_sha(dst):
            raise SystemExit("复制校验失败，字节不一致: %s" % f)

    # 清理上一次构建遗留的对照图（该目录完全由本脚本生成）
    if not args.skip_assets:
        for fn in os.listdir(pair_dir):
            if fn.lower().endswith(".png"):
                os.remove(os.path.join(pair_dir, fn))

    made = []
    for p in res["pairs"]:
        name = "%s__%s.png" % (p["a"][:-4], p["b"][:-4])
        dst = os.path.join(pair_dir, name)
        if not (args.skip_assets and os.path.exists(dst)):
            make_composite(dst, res["imgs"][p["a"]], res["imgs"][p["b"]],
                           p["_raw_diff"], p["_aligned_diff"], p["_aligned_mask"],
                           p["_gain_raw"], p["_gain_aligned"])
        made.append(name)
    return made


# --------------------------------------------------------------------------- #
# 输出数据
# --------------------------------------------------------------------------- #
def write_checksums(out):
    data_dir = os.path.join(out, "data")
    os.makedirs(data_dir, exist_ok=True)
    files = []
    for root, dirs, fnames in os.walk(out):
        dirs[:] = sorted(d for d in dirs if d != "__pycache__")
        for fn in sorted(fnames):
            if fn == "checksums.sha256" or fn.endswith(".pyc"):
                continue
            path = os.path.join(root, fn)
            files.append((os.path.relpath(path, out), file_sha(path)))
    files.sort()
    with open(os.path.join(data_dir, "checksums.sha256"), "w", encoding="utf-8") as fh:
        for rel, h in files:
            fh.write("%s  %s\n" % (h, rel))


def write_data(res):
    out = res["out_root"]
    data_dir = os.path.join(out, "data")
    os.makedirs(data_dir, exist_ok=True)
    imgs = res["imgs"]
    pairs = res["pairs"]

    write_csv(
        os.path.join(data_dir, "hashes.csv"),
        ["name", "bytes", "width", "height", "sha256", "pixel_sha256",
         "ahash64", "dhash64", "phash64", "bmvhash256", "unique_colors",
         "mean_r", "mean_g", "mean_b"],
        [[imgs[n]["name"], imgs[n]["bytes"], imgs[n]["width"], imgs[n]["height"],
          imgs[n]["sha256"], imgs[n]["pixel_sha256"], imgs[n]["ahash"],
          imgs[n]["dhash"], imgs[n]["phash"], imgs[n]["bmvhash"],
          imgs[n]["unique_colors"]] + imgs[n]["mean_rgb"] for n in res["names"]],
    )

    write_csv(
        os.path.join(data_dir, "pairs.csv"),
        ["a", "b", "verdict", "exact_byte", "pixel_equal",
         "bmvhash_hamming", "ahash_hamming", "dhash_hamming", "phash_hamming",
         "ssim", "mae", "rmse", "max_abs", "pct_over_tol", "tol",
         "shift_offset_x", "shift_offset_y", "aligned_mae", "aligned_max_abs",
         "aligned_pct_over_tol", "gates_passed", "summary"],
        [[p["a"], p["b"], p["verdict"], p["exact_byte"], p["pixel_equal"],
          p["bmv"], p["ah"], p["dh"], p["ph"], "%.6f" % p["ssim"],
          "%.6f" % p["mae"], "%.6f" % p["rmse"], p["max_abs"],
          "%.4f" % p["pct_over_tol"], p["tol"],
          p["shift"]["offset_x"], p["shift"]["offset_y"],
          "%.6f" % p["aligned"]["mae"], p["aligned"]["max_abs"],
          "%.4f" % p["aligned"]["pct_over_tol"],
          sum(1 for k in ("bmv", "ah", "dh", "ssim") if p["gates"][k]),
          p["summary"]] for p in pairs],
    )

    write_csv(
        os.path.join(data_dir, "groups.csv"),
        ["group_id", "group_type", "size", "members", "canonical", "evidence",
         "min_intra_bmv", "max_intra_bmv", "min_intra_ssim", "note"],
        [[g["group_id"], g["group_type"], g["size"], g["members"], g["canonical"],
          g["evidence"], g["min_intra_bmv"], g["max_intra_bmv"],
          g["min_intra_ssim"], g["note"]]
         for g in res["group_rows"]],
    )

    write_csv(
        os.path.join(data_dir, "recommendations.csv"),
        ["file", "group_id", "group_type", "role", "action", "reason", "backup_required"],
        [[r["file"], r["group_id"], r["group_type"], r["role"], r["action"],
          r["reason"], r["backup_required"]] for r in res["rec_rows"]],
    )

    write_json(os.path.join(data_dir, "groups.json"), {
        "schema": "d45-groups/1",
        "tool": {"name": TOOL_NAME, "version": TOOL_VERSION},
        "rule": "exact = SHA-256 equal; near = bmv<=bmv_max and ah<=ahash_max and "
                "dh<=dhash_max and ssim>=ssim_min (optional pHash gate).",
        "thresholds": res["th"],
        "inputs": {"dir": os.path.relpath(res["inputs"], out), "files": res["names"]},
        "exact_groups": res["exgroups"],
        "near_groups": res["near_groups"],
        "singletons": res["singles"],
        "clique_violations": res["clique_violations"],
        "group_rows": res["group_rows"],
        "validation": res["validation"],
    })

    write_json(os.path.join(data_dir, "pairs.json"), {
        "schema": "d45-pairs/1",
        "tool": {"name": TOOL_NAME, "version": TOOL_VERSION},
        "thresholds": res["th"],
        "tol": res["tol"],
        "pairs": [{k: v for k, v in p.items() if not k.startswith("_")}
                  for p in res["pairs"]],
    })

    analysis = {
        "schema": "d45-analysis/1",
        "tool": {"name": TOOL_NAME, "version": TOOL_VERSION,
                 "python": sys.version.split()[0], "stdlib_only": True},
        "inputs": {
            "dir": os.path.relpath(res["inputs"], out),
            "count": len(res["names"]),
            "files": [{k: v for k, v in imgs[n].items() if not k.startswith("_")}
                      for n in res["names"]],
        },
        "parameters": {"thresholds": res["th"], "tol": res["tol"],
                       "linkage": "single", "phash_gate_default": res["th"]["phash"]},
        "metrics_table": res["metrics_table"],
        "stable_intervals": {k: {kk: vv for kk, vv in v.items() if kk != "values"}
                             for k, v in res["stable"].items()},
        "phash_gate_demo": res["ph_demo"],
        "single_metric_stable": res["single"],
        "joint_relax_demo": res["joint_demo"],
        "pairs": [{k: v for k, v in p.items() if not k.startswith("_")}
                  for p in res["pairs"]],
        "groups": {"exact": res["exgroups"], "near": res["near_groups"],
                   "singletons": res["singles"],
                   "clique_violations": res["clique_violations"]},
        "group_rows": res["group_rows"],
        "retention": res["rec_rows"],
        "validation": res["validation"],
        "examples": res.get("examples"),
        "rename_experiment": res.get("rename_test"),
    }
    write_json(os.path.join(data_dir, "analysis.json"), analysis)
    return analysis


# --------------------------------------------------------------------------- #
def main(argv=None):
    ap = argparse.ArgumentParser(description="D45 图像重复检测构建脚本")
    ap.add_argument("--inputs", default=os.path.join(OUT_ROOT, "..", "inputs", "images"),
                    help="输入图片目录（只读）")
    ap.add_argument("--out", default=OUT_ROOT, help="输出根目录（默认 outputs/）")
    ap.add_argument("--spec", default=os.path.join(OUT_ROOT, "..", "inputs", "spec.json"),
                    help="验收真值 spec.json（可选，只用于比对）")
    ap.add_argument("--bmv-max", type=int, default=DEFAULTS["bmv_max"],
                    help="块均值哈希(bmvhash-256)汉明距离上限")
    ap.add_argument("--ahash-max", type=int, default=DEFAULTS["ahash_max"],
                    help="均值哈希(aHash-64)汉明距离上限")
    ap.add_argument("--dhash-max", type=int, default=DEFAULTS["dhash_max"],
                    help="差值哈希(dHash-64)汉明距离上限")
    ap.add_argument("--ssim-min", type=float, default=DEFAULTS["ssim_min"],
                    help="分块 SSIM 下限")
    ap.add_argument("--phash-max", type=int, default=None,
                    help="可选：额外要求 pHash-64 距离不超过该值（默认不启用）")
    ap.add_argument("--tol", type=int, default=DEFAULTS["tol"],
                    help="像素差计数阈值（通道差 > tol 记为差异像素）")
    ap.add_argument("--skip-assets", action="store_true",
                    help="跳过已存在的原图副本/对照图重写")
    ap.add_argument("--check", action="store_true", help="打印验收比对结果")
    ap.add_argument("--no-rename-test", action="store_true",
                    help="跳过改名实验（默认执行：复制成随机文件名重跑，验证与文件名无关）")
    args = ap.parse_args(argv)

    res = build(args)
    if not args.no_rename_test:
        res["rename_test"] = rename_experiment(args, res)
    write_assets(res, args)
    analysis = write_data(res)

    import report
    import webrender
    report.write_readme(res, analysis)
    webrender.write_index(res, analysis)
    write_checksums(res["out_root"])

    if args.check:
        v = res["validation"]
        if v is None:
            print("未找到 spec.json，跳过验收比对")
        else:
            print("精确组匹配:", "PASS" if v["exact_match"] else "FAIL")
            print("近似组匹配:", "PASS" if v["near_match"] else "FAIL")
            for g in res["near_groups"]:
                print("  近似组:", ", ".join(g))
            for g in res["singles"]:
                print("  孤立:", g)
    print("构建完成 -> %s" % os.path.abspath(args.out))
    print("阈值: bmv<=%s, ah<=%s, dh<=%s, ssim>=%s, phash=%s, tol=%s"
          % (res["th"]["bmv"], res["th"]["ah"], res["th"]["dh"],
             res["th"]["ssim"], res["th"]["phash"], res["tol"]))
    print("分组: %d 组（含孤立），精确组 %d 个，近似组 %d 个"
          % (len(res["groups"]), len(res["exgroups"]), len(res["near_groups"])))


if __name__ == "__main__":
    main()