#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""南部大区经营日报·按钮式播报发送（2026-10-16 用户定稿格式）。
用法：python3 南部大区城市看板/send_card.py [--dry] [--to original|battle|all|test]
- 卡片=actionCard：📱 **手机按钮**（hailuo-ai 单文档路径，钉钉内免登全屏）+ 正文字段「[🏢 稳定链接（需登录）]（jarvis 发布中心详情页，
  PC 端点击跳系统浏览器）**不得做成按钮**——PC 端按钮会被钉钉内嵌面板打开成「加载失败」+ 末行备用隧道链接。
- 发前每个 webhook 先 {} 探活（40035=健康）。
"""
import json, subprocess, sys, urllib.request

K = '/data/workspace/南部大区城市看板'
CFG = json.load(open(f'{K}/config/broadcast.json', encoding='utf-8'))
TEST = json.load(open('/data/workspace/prep_ticket_dashboard/config/broadcast.json', encoding='utf-8'))


def card_text():
    r = subprocess.run(['python3', f'{K}/build_card.py', '--no-links'],
                       capture_output=True, text=True, cwd='/data/workspace')
    if r.returncode != 0:
        sys.exit('[FAIL] build_card.py: ' + r.stderr[-400:])
    return r.stdout.strip()


def build_payload():
    text = card_text()
    tail = [f'[🏢 稳定链接（需登录）]({CFG["desktop_url"]})',
            f'备用（免登录·隧道）：[点击打开]({CFG["intranet_url"]})']
    title = text.split('\n\n')[0].replace('*', '').lstrip('# ').strip()
    return {'msgtype': 'actionCard', 'actionCard': {
        'title': title, 'text': text + '\n\n' + '\n\n'.join(tail), 'btnOrientation': '1',
        'btns': [{'title': '📱 手机打开看板', 'actionURL': CFG['mobile_url']}]}}


def targets(sel):
    # 2026-10-16 定稿：日常播报只发作战群；测试群（原群）仅手动 --to test 验证用
    main = [(CFG['group_name'], CFG['webhook'])]
    if sel in ('all', 'original', 'battle'):
        return main
    if sel == 'test':
        tt = CFG.get('test_targets') or [{'group_name': '测算群（测试）', 'webhook': TEST['webhook']}]
        return [(x['group_name'], x['webhook']) for x in tt]
    sys.exit(f'[FAIL] --to 取值非法: {sel}（可用：original|all|battle|test）')


def post(url, payload, timeout=30):
    req = urllib.request.Request(url, data=json.dumps(payload).encode(),
                                 headers={'Content-Type': 'application/json'}, method='POST')
    return json.load(urllib.request.urlopen(req, timeout=timeout))


def main():
    sel = sys.argv[sys.argv.index('--to') + 1] if '--to' in sys.argv else 'original'
    p = build_payload()
    if '--dry' in sys.argv:
        print(p['actionCard']['text'])
        print('\n【按钮】', [b['title'] + ' -> ' + b['actionURL'] for b in p['actionCard']['btns']])
        print('【目标】', [n for n, _ in targets(sel)])
        return
    fails = 0
    for name, url in targets(sel):
        try:
            pr = post(url, {})
            healthy = pr.get('errcode') == 40035
        except Exception as e:
            pr, healthy = repr(e), False
        print(f'[PROBE] {name} -> {"OK(40035)" if healthy else "FAIL " + str(pr)[:140]}')
        if not healthy:
            fails += 1
            continue
        try:
            r = post(url, p)
        except Exception as e:
            print('[FAIL]', name, repr(e)); fails += 1; continue
        print(('[SENT] ' if r.get('errcode') == 0 else '[FAIL] ') + name, r)
        if r.get('errcode') != 0:
            fails += 1
    sys.exit(1 if fails else 0)


main()
