#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""线上复核：隧道 API 是否带出 departments，CDN 页面是否有下钻 UI。"""
import json
import ssl
import sys
import urllib.request

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
CDN = 'https://bier-sales-d0gatbvlx288724e9-1458438710.tcloudbaseapp.com/workbench/index.html'
TUN = 'https://api.biorisales.site:8443'
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

sess = json.load(open(ROOT + '/数据/auth_sessions.json', encoding='utf-8'))
mine = sorted([(v['expire_at'], k, v) for k, v in sess.items() if v.get('name') == '刘新元'], reverse=True, key=lambda x: x[0])
TOKEN = mine[0][1]

ok = True
def chk(label, cond, detail=''):
    global ok
    print('  %s %-42s %s' % ('✅' if cond else '❌', label, detail))
    if not cond:
        ok = False

print('① 隧道 API 是否带 departments（线上后端已更新）')
req = urllib.request.Request(TUN + '/api/visit/stats?month=2026-10&scope=team')
req.add_header('Authorization', 'Bearer ' + TOKEN)
try:
    with urllib.request.urlopen(req, timeout=30, context=ctx) as r:
        j = json.load(r)
    keys = sorted(j.keys())
    chk('HTTP 200 + ok', j.get('ok'), str(j.get('error', ''))[:50])
    chk('响应含 departments', 'departments' in j, '键: ' + ','.join(keys)[:110])
    chk('响应含 trend', 'trend' in j, str(len(j.get('trend') or [])) + ' 个月')
    chk('响应含 scope/can_team', 'scope' in j and 'can_team' in j, 'scope=%s can_team=%s' % (j.get('scope'), j.get('can_team')))
    chk('admin 可用 team 范围', j.get('can_team') is True)
except Exception as e:
    chk('隧道 API 调用', False, str(e)[:90])

print('\n② CDN 页面是否含下钻 UI')
try:
    b = urllib.request.urlopen(urllib.request.Request(CDN, headers={'User-Agent': 'probe'}), timeout=25, context=ctx).read().decode('utf-8', 'ignore')
    for kw, name in [('visitSetDim', '维度切换函数'), ('visitDrillTo', '下钻函数'),
                     ('visitCrumB'.replace('C', 'c') if False else 'visitCrumb', '面包屑'),
                     ('departments', '读取 departments'), ('按部门', '按部门按钮文案')]:
        chk('线上含 %s' % name, kw in b, kw)
except Exception as e:
    chk('CDN 页面取回', False, str(e)[:80])

print('\n%s' % ('✅ 线上三级下钻管道已就绪' if ok else '❌ 线上有问题'))
sys.exit(0 if ok else 1)
