#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把手册 v3 的「常用速查 10 句 + 权限说明」推送给刘子研（微信）。

前提：iLink 要求「用户先给机器人发过消息」才有 context_token，否则机器人主动发送会被拒
（源码 §83: prepare a bot-initiated send until this peer messages the bot again）。
本脚本会：① 从 v3 HTML 抽出速查句与说明 ② 组装微信友好纯文本 ③ 尝试发送并如实打印结果。
"""
import asyncio
import json
import os
import re
import sys

sys.path.insert(0, os.path.expanduser('~/.hermes/hermes-agent'))
from gateway.platforms.weixin import _new_session, _send_message  # noqa: E402

W = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
SRC = os.path.join(W, '团队共享/宝锐销售助手_使用手册_v3展示优化DEMO.html')
PROF = os.path.expanduser('~/.hermes/profiles/baorui-sales')
ACC = 'cc49fa005f05@im.bot'
PEER = 'o9cq807eWLFtVvCrznpCX6OQmR5w@im.wechat'


def build_text():
    h = open(SRC, encoding='utf-8').read()
    # 10 条速查句（.ql 里的 .qq 文本）
    quicks = [re.sub(r'<[^>]+>', '', m).strip()
              for m in re.findall(r'<span class="qq">(.*?)</span>', h, re.S)]
    note = re.search(r'<div class="note">(.*?)</div>', h, re.S)
    note_txt = re.sub(r'<br\s*/?>', '\n', note.group(1)) if note else ''
    note_txt = re.sub(r'<[^>]+>', '', note_txt)
    note_lines = [l.strip(' ·') for l in note_txt.split('\n') if l.strip() and l.strip() != '·']
    lines = ['宝锐销售助手 · 常用速查（直接抄）', '']
    for i, q in enumerate(quicks, 1):
        lines.append('%d）%s' % (i, q))
    lines += ['', '—— 说明 ——']
    for l in note_lines:
        lines.append('· ' + re.sub(r'\s+', ' ', l))
    return '\n'.join(lines).strip(), quicks, note_lines


def main():
    text, quicks, notes = build_text()
    print('=== 组装好的消息（%d 字，速查 %d 条）===' % (len(text), len(quicks)))
    print(text)
    print()
    tok = json.load(open(os.path.join(PROF, 'weixin/accounts/%s.json' % ACC), encoding='utf-8'))
    base = tok['base_url']
    ctx_file = os.path.join(PROF, 'weixin/accounts/%s.context-tokens.json' % ACC)
    ctx = None
    if os.path.exists(ctx_file):
        d = json.load(open(ctx_file, encoding='utf-8'))
        ctx = d.get('%s:%s' % (ACC, PEER))
        print('context_token（她与我们最近的会话凭据）:', '有' if ctx else '无')
    else:
        print('context_token 文件不存在 → 她从没给这个新助手发过消息')
    print()

    async def send():
        async with _new_session() as s:
            try:
                r = await _send_message(s, base_url=base, token=tok['token'], to=PEER,
                                        text=text, context_token=ctx, client_id='manual-push-quickref-1')
                print('发送结果:', json.dumps(r, ensure_ascii=False)[:300])
                return r
            except Exception as e:
                print('发送异常:', str(e)[:300])
                return None

    res = asyncio.run(send())
    ok = bool(res) and not (isinstance(res, dict) and res.get('errcode') and res.get('errcode') != 0)
    print()
    print('判定:', '✅ 已推送' if ok else '❌ 未能推送（大概率是她还没给助手发过消息 → 无 context_token）')
    open(os.path.join(W, '团队共享/_推送内容_常用速查10句.txt'), 'w', encoding='utf-8').write(text)
    print('（同一份内容已存: 团队共享/_推送内容_常用速查10句.txt）')


if __name__ == '__main__':
    main()
