#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""线上 vs 本地 md5 校验（CloudBase 静态托管）。
用法: python3 verify_cb_sync.py            # 只校验
      python3 verify_cb_sync.py --deploy   # 先部署 MISS/DIFF 的文件再校验
中文路径全部在本脚本内 URL 编码，避免命令行出现非 ASCII URL 被 cron 守卫拦。
"""
import hashlib
import os
import subprocess
import sys
import time
import urllib.parse
import urllib.request

CDN = 'https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com'
ENV = 'bier-sales-d0gatbvlx288724e9'
DATA = os.path.expanduser('~/Desktop/Hermes输出-工作类/数据')
# 远端路径(相对站点根) → 本地文件
TARGETS = [
    ('数据/workbench_data.json', 'workbench_data.json'),
    ('数据/kpi_dashboard.json', 'kpi_dashboard.json'),
    ('数据/kpi_progress.json', 'kpi_progress.json'),
    ('数据/shipment_status.json', 'shipment_status.json'),
    ('数据/my_activities.json', 'my_activities.json'),
    ('数据/customer_360.json', 'customer_360.json'),
    ('数据/file_manifest.json', 'file_manifest.json'),
    ('数据/pricing/_key_customers.json', 'pricing/_key_customers.json'),
    ('数据/mcp_customers.json', 'mcp_customers.json'),
    ('数据/mcp_complaints.json', 'mcp_complaints.json'),
]


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


def remote(rel):
    url = CDN + '/' + urllib.parse.quote(rel) + '?v=%d' % int(time.time())
    req = urllib.request.Request(url, headers={'Cache-Control': 'no-cache', 'Pragma': 'no-cache'})
    with urllib.request.urlopen(req, timeout=120) as r:
        return r.read()


def main():
    deploy = '--deploy' in sys.argv
    rows = []
    for rel, loc in TARGETS:
        p = os.path.join(DATA, loc)
        if not os.path.exists(p):
            rows.append((rel, '-', '-', 'NO_LOCAL'))
            continue
        lb = open(p, 'rb').read()
        lm = md5(lb)
        try:
            rm = md5(remote(rel))
        except Exception as e:
            rm = 'ERR:%s' % str(e)[:40]
        status = 'SAME' if lm == rm else 'DIFF'
        rows.append((rel, lm[:12], (rm if rm.startswith('ERR') else rm[:12]), status))

    for rel, lm, rm, st in rows:
        print('%-40s local=%-14s remote=%-14s %s' % (rel, lm, rm, st))

    bad = [r for r in rows if r[3] not in ('SAME',)]
    if deploy and bad:
        print('\n--- 部署 DIFF/MISS 文件 ---')
        for rel, _, _, _ in bad:
            loc = dict(TARGETS)[rel]
            src = os.path.join(DATA, loc)
            if not os.path.exists(src):
                continue
            r = subprocess.run(['tcb', 'hosting', 'deploy', src, rel, '-e', ENV],
                               capture_output=True, text=True, timeout=900)
            ok = '✔' in (r.stdout + r.stderr)
            print('%-40s %s' % (rel, 'deployed' if ok else 'FAILED: ' + (r.stderr or r.stdout)[-160:]))
        time.sleep(2)
        print('\n--- 复验 ---')
        for rel, loc, _, _ in [(r[0], dict(TARGETS)[r[0]], 0, 0) for r in bad]:
            try:
                rm = md5(remote(rel))
            except Exception as e:
                rm = 'ERR:%s' % str(e)[:40]
            lm = md5(open(os.path.join(DATA, loc), 'rb').read())
            print('%-40s %s' % (rel, 'SAME ✅' if lm == rm else 'STILL DIFF ❌ local=%s remote=%s' % (lm[:12], rm[:12])))
    print('\nSUMMARY: %d targets, %d not in sync' % (len(rows), len(bad)))


main()
