#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""6b 部署验真：线上回读 8 个数据文件，比本地 md5 + _merged_at。
中文路径用 quote 编码（cron curl 安全闸）。
"""
import hashlib
import json
import time
import urllib.parse
import urllib.request
from pathlib import Path

BASE = "https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com"
DATA = Path.home() / "Desktop/Hermes输出-工作类/数据"
FILES = [
    "kpi_dashboard.json",
    "kpi_progress.json",
    "workbench_data.json",
    "shipment_status.json",
    "my_activities.json",
    "customer_360.json",
    "file_manifest.json",
    "pricing/_key_customers.json",
]


def online(path, attempts=6):
    """下载线上文件。本机链路会把大文件中途截断（Content-Length 达标但 read 提前结束），
    故按 Content-Length 校验长度并重试，长度达标才返回。"""
    last = None
    for i in range(attempts):
        url = BASE + "/" + urllib.parse.quote("数据/" + path) + f"?t={int(time.time())}"
        try:
            req = urllib.request.Request(url, headers={
                "Cache-Control": "no-cache", "Accept-Encoding": "identity",
                "User-Agent": "verify"})
            with urllib.request.urlopen(req, timeout=180) as r:
                clen = int(r.headers.get("Content-Length") or 0)
                data = r.read()
            if clen and len(data) != clen:
                last = f"长度不足 {len(data)}/{clen}"
                time.sleep(2)
                continue
            return data
        except Exception as e:
            last = f"{type(e).__name__}: {e}"
            time.sleep(2)
    raise RuntimeError(f"下载 {attempts} 次仍不完整（{last}）")


ok = 0
for f in FILES:
    lp = DATA / f
    if not lp.exists():
        print(f"⚠️ 本地缺失 {f}")
        continue
    local = lp.read_bytes()
    lmd5 = hashlib.md5(local).hexdigest()
    try:
        remote = online(f)
        rmd5 = hashlib.md5(remote).hexdigest()
        same = "✅ MD5一致" if lmd5 == rmd5 else "❌ MD5不一致"
        extra = ""
        if f.endswith(".json"):
            try:
                d = json.loads(remote)
                if isinstance(d, dict):
                    for k in ("_merged_at", "updated_at", "updated"):
                        if k in d:
                            extra += f" {k}={d[k]}"
            except Exception:
                pass
        print(f"{same} {f} local={lmd5[:12]} online={rmd5[:12]} "
              f"{len(local)/1024:.0f}KB/{len(remote)/1024:.0f}KB{extra}")
        ok += lmd5 == rmd5
    except Exception as e:
        print(f"❌ 回读失败 {f}: {type(e).__name__}: {e}")

print(f"\n一致 {ok}/{len(FILES)}")
