#!/usr/bin/env python3
"""Verify CloudBase CDN deployment by reading back the deployed JSON files.

Usage: python3 _verify_deploy.py
Note: URL path contains Chinese -> percent-encoded here (cron curl safety gate).
"""
import json, urllib.request, time

BASE = "https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com"
DATA = "%E6%95%B0%E6%8D%AE"   # 数据

def fetch(path, tries=3):
    url = f"{BASE}/{path}?t={int(time.time())}"
    for i in range(tries):
        try:
            req = urllib.request.Request(url, headers={"Cache-Control": "no-cache", "User-Agent": "verify"})
            with urllib.request.urlopen(req, timeout=60) as r:
                return json.loads(r.read())
        except Exception as e:
            if i == tries - 1:
                return {"_error": f"{type(e).__name__}: {e}"}
            time.sleep(3)

out = {}

d = fetch(f"{DATA}/workbench_data.json")
if "_error" in d:
    out["workbench_data"] = d
else:
    out["workbench_data"] = {
        "_merged_at": d.get("_merged_at"),
        "complaints": (d.get("complaints") or {}).get("total"),
        "customers": len(((d.get("mcpCustomers") or {}).get("customers")) or []),
        "shipments": (d.get("shipments") or {}).get("total"),
    }

d2 = fetch(f"{DATA}/mcp_customers.json")
out["cdn_mcp_customers"] = {"_error": d2["_error"]} if "_error" in d2 else {
    "updated_at": d2.get("updated_at"), "count": len(d2.get("customers") or [])}

d3 = fetch(f"{DATA}/mcp_complaints.json")
out["cdn_mcp_complaints"] = {"_error": d3["_error"]} if "_error" in d3 else {
    "updated": d3.get("updated"), "total": d3.get("total"), "items": len(d3.get("items") or [])}

d4 = fetch(f"{DATA}/shipment_status.json")
out["cdn_shipment_status"] = {"_error": d4["_error"]} if "_error" in d4 else {
    "total": d4.get("total"), "updated": d4.get("updated")}

print(json.dumps(out, ensure_ascii=False, indent=1))
