#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""线上复核（P2c）：控件收敛是否上线 + 隧道 API 是否带出飞书 9 月基础数据。"""
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'))
TOKEN = sorted([(v['expire_at'], k) for k, v in sess.items() if v.get('name') == '刘新元'],
               reverse=True)[0][1]

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

print('① 隧道 API：9 月飞书基础数据是否并入')
req = urllib.request.Request(TUN + '/api/visit/stats?month=2026-09&scope=team')
req.add_header('Authorization', 'Bearer ' + TOKEN)
try:
    with urllib.request.urlopen(req, timeout=60, context=ctx) as r:
        j = json.load(r)
    chk('HTTP 200 + ok', j.get('ok'))
    chk('总数 2093（9 月）', j.get('total') == 2093, str(j.get('total')))
    chk('线下 403 / 线上 67', (j.get('offline_count'), j.get('online_count')) == (403, 67),
        '%s/%s' % (j.get('offline_count'), j.get('online_count')))
    chk('可判定率 22.5%', (j.get('channel_judge') or {}).get('rate') == 22.5, str(j.get('channel_judge')))
    chk('来源含飞书 2093', (j.get('src_breakdown') or {}).get('feishu') == 2093, str(j.get('src_breakdown')))
    deps = {d['dept']: d for d in (j.get('departments') or [])}
    chk('4 个部门（无「未匹配部门」）', len(deps) == 4 and '未匹配部门' not in deps, '、'.join(deps))
    chk('守恒：线下之和==KPI', sum(d['offline'] for d in deps.values()) == j.get('offline_count'))
    ls = deps.get('生命科学销售部') or {}
    cch = [s for s in (ls.get('sales') or []) if s['name'] == '陈彩红']
    chk('陈彩红 归入生命科学销售部/广东', bool(cch) and cch[0].get('region') == '广东',
        ('%s %s 活动%s' % (cch[0]['name'], cch[0]['region'], cch[0]['total'])) if cch else '未找到')
    chk('活动明细行带 src（飞书标签依赖）',
        all('src' in a for d in deps.values() for s in (d.get('sales') or [])
            for c in (s.get('customers') or []) for a in (c.get('acts') or [])[:3]))
except Exception as e:
    chk('隧道 API', False, str(e)[:100])

print('\n② CDN 页面：控件收敛是否上线')
try:
    b = urllib.request.urlopen(urllib.request.Request(CDN, headers={'User-Agent': 'probe'}),
                               timeout=30, context=ctx).read().decode('utf-8', 'ignore')
    chk('含新控件 visitSetView', 'visitSetView' in b)
    chk('含「按部门」文案', '按部门' in b)
    chk('含「按客户」文案', '按客户' in b)
    chk('含面包屑 visitCrumb', 'visitCrumb' in b)
    chk('已无旧的 visitSetDim', 'visitSetDim' not in b)
    chk('已无「👥 全队」按钮（注释提及不算）', '👥 全队' not in b and 'visitSetScope' not in b,
        '全队出现次数=%d（应仅为注释）' % b.count('全队'))
    chk('仍含 wbReq 绝对基址', 'wbReq' in b and 'AUTH_APIS' in b)
except Exception as e:
    chk('CDN 页面取回', False, str(e)[:90])

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