#!/usr/bin/env python3
"""Step6 收尾校验：CDN 回读比对本地 md5（cron 临时探针）"""
import hashlib, json, os, time, urllib.parse, urllib.request

BASE = "https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com"
DATA = os.path.expanduser("~/Desktop/Hermes输出-工作类/数据")
FILES = [
    "workbench_data.json", "mcp_customers.json", "mcp_complaints.json",
    "shipment_status.json", "kpi_progress.json", "customer_360.json",
]
NOTE = {"daily_activities_mcp.json": "中间产物，CDN 缺失/过期属设计如此（无线上页面直接 fetch）"}


def md5b(b):
    return hashlib.md5(b).hexdigest()


ok = 0
for f in FILES:
    lp = os.path.join(DATA, f)
    lb = open(lp, "rb").read()
    cp = urllib.parse.quote("数据/" + f)
    url = f"{BASE}/{cp}?v={int(time.time())}"
    try:
        req = urllib.request.Request(url, headers={"Cache-Control": "no-cache", "User-Agent": "verify"})
        rb = urllib.request.urlopen(req, timeout=120).read()
    except Exception as e:
        print(f"{f}: ❌ 拉取失败 ({e})")
        continue
    same = md5b(lb) == md5b(rb)
    ok += same
    print(f"{f}: {'✅一致' if same else '⚠️不一致'} local={len(lb)}B remote={len(rb)}B")
    if f == "workbench_data.json" and same:
        d = json.loads(rb)
        print("    _merged_at:", d.get("_merged_at"),
              "| complaints:", len(d.get("complaints", {}).get("items", [])),
              "| mcpCustomers:", len(d.get("mcpCustomers", {}).get("customers", [])),
              "| shipments:", d.get("shipments", {}).get("total"))
    if f == "mcp_customers.json" and same:
        d = json.loads(rb)
        print("    updated_at:", d.get("updated_at"), "| customers:", len(d.get("customers", [])))
    if f == "mcp_complaints.json" and same:
        d = json.loads(rb)
        print("    客诉:", len(d.get("items", [])))

print(f"\nCDN 一致 {ok}/{len(FILES)}")
for k, v in NOTE.items():
    print(f"（说明）{k}: {v}")
