#!/usr/bin/env python3
"""车队后端版本滚动进度表。数据源：cloud-v2 的 deviceLog/list（每台每 5 分钟上报）。

用法:
    python3 scripts/fleet-rollout-status.py 1.9.62        # 看向 1.9.62 铺开的进度
    python3 scripts/fleet-rollout-status.py 1.9.62 --behind   # additionally 列出落后设备
    python3 scripts/fleet-rollout-status.py               # 不给目标版本则只看分布
"""
import sys, json, time, urllib.request
from collections import Counter

LIST_URL = "https://cloud-v2.aaden.io/deviceLog/list"
STALE_MIN = 30  # 超过这么多分钟没上报，视为离线/失联

def fetch():
    with urllib.request.urlopen(LIST_URL, timeout=60) as r:
        return json.load(r)

def main():
    target = next((a for a in sys.argv[1:] if not a.startswith('-')), None)
    show_behind = '--behind' in sys.argv
    d = fetch()
    now = int(time.time() * 1000)
    total = len(d)
    dist = Counter(x.get('backendVersion', '?') for x in d)
    stale = [x for x in d if now - int(x.get('timestamp', 0) or 0) > STALE_MIN * 60 * 1000]

    print(f"车队共 {total} 台   (数据源 deviceLog/list，每台每 5 分钟上报)")
    print(f"失联(>{STALE_MIN}分钟无上报): {len(stale)} 台")
    print()
    if target:
        on = [x for x in d if x.get('backendVersion') == target]
        behind = [x for x in d if x.get('backendVersion') != target]
        pct = len(on) * 100.0 / total if total else 0
        bar = '#' * int(pct // 2.5) + '.' * (40 - int(pct // 2.5))
        print(f"目标后端版本: {target}")
        print(f"  已到位  [{bar}] {len(on)}/{total}  {pct:.1f}%")
        print(f"  未到位  {len(behind)} 台")
        print()
        print("未到位版本分布:")
        for v, n in Counter(x.get('backendVersion', '?') for x in behind).most_common():
            print(f"    {v:>10}  {n} 台")
        if show_behind:
            print()
            print("未到位设备(deviceId / 版本 / 名称首行):")
            for x in sorted(behind, key=lambda x: x.get('deviceId', '')):
                name = (x.get('deviceName') or '').split('\n')[0][:32]
                print(f"    {str(x.get('deviceId','?')):>6}  {x.get('backendVersion','?'):>10}  {name}")
    else:
        print("后端版本分布:")
        for v, n in dist.most_common():
            print(f"    {v:>10}  {n} 台")

if __name__ == '__main__':
    main()
