#!/usr/bin/env python3
"""
RBTC — third-party verification script

Use: anyone holding an RBTC image can check it against the official build.
用法：
    python3 verify.py <图片目录>
    python3 verify.py ./images

不信任任何一方，只信任数学。全部本地计算，不联网。
"""
import sys, os, json, hashlib

FILES_ROOT   = "0e4f172b361f535214b1a7e4b2b8741666bca5007a6817abceb4f108e5dbac96"
TRAITS_ROOT  = "854a1a39b7cb398dd1ec4586b0c7879d6ec319599d0f45ca2bc731400e4b17e8"
EXPECTED     = 2222


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


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return 2
    d = sys.argv[1]
    if not os.path.isdir(d):
        print("错误：目录不存在 ->", d)
        return 2

    # 找清单：同级或 _meta/ 下
    cand = [os.path.join(d, "files_manifest.json"),
            os.path.join(d, "_meta", "files_manifest.json"),
            os.path.join(os.path.dirname(d.rstrip("/")), "_meta", "files_manifest.json"),
            "files_manifest.json"]
    mpath = next((c for c in cand if os.path.isfile(c)), None)
    if not mpath:
        print("错误：找不到 files_manifest.json")
        print("请从官方发布包中一并下载，放在图片目录或 _meta/ 下。")
        return 2

    raw = open(mpath, "rb").read()
    root = hashlib.sha256(raw).hexdigest()
    print("清单文件 :", mpath)
    print("实测根哈希:", root)
    print("官方根哈希:", FILES_ROOT)
    if root != FILES_ROOT:
        print("\n[x] 清单本身与官方记录不符 —— 停止。这份清单不可信。")
        return 1
    print("[√] 清单本身通过验证\n")

    files = json.loads(raw)["files"]
    if len(files) != EXPECTED:
        print("[x] 清单条目数异常:", len(files), "应为", EXPECTED)
        return 1

    ok, bad, missing = 0, [], []
    for e in files:
        p = os.path.join(d, e["file"])
        if not os.path.isfile(p):
            missing.append(e["file"]); continue
        if sha256_file(p) == e["sha256"]:
            ok += 1
        else:
            bad.append(e["file"])

    print("逐张核对结果")
    print("  通过 :", ok)
    print("  不符 :", len(bad))
    print("  缺失 :", len(missing))
    if bad:
        print("\nMISMATCHED files (not part of the original RBTC build):")
        for f in bad[:20]:
            print("   -", f)
        if len(bad) > 20:
            print("   ...还有", len(bad) - 20, "个")
    if missing:
        print("\n缺失的文件：")
        for f in missing[:20]:
            print("   -", f)

    if ok == EXPECTED and not bad and not missing:
        print("\n[OK] all 2222 files verified. Original RBTC build intact.")
        return 0
    print("\n[x] 未通过 —— 存在改动或缺失。")
    return 1


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