#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import asyncio, base64, glob, hashlib, json, os, secrets, sys, time
from pathlib import Path
from urllib.parse import quote

# 载入 Hermes 自带 weixin 模块
mods=glob.glob(os.path.expanduser('~/.hermes/installs/*/environments/*/workspace'))
for m in mods:
    if os.path.isdir(os.path.join(m,'gateway','platforms')):
        sys.path.insert(0,m); break
from gateway.platforms import weixin as wx

PROFILE=os.path.expanduser('~/.hermes/profiles/baorui-sales')
ACC=os.path.join(PROFILE,'weixin/accounts/cc49fa005f05@im.bot.json')
cred=json.load(open(ACC,encoding='utf-8'))
token=cred['token']; base_url=cred['base_url'].rstrip('/'); cdn_base=cred.get('cdn_base_url','https://novac2c.cdn.weixin.qq.com/c2c').rstrip('/')
account_id=os.path.basename(ACC).split('@')[0]
to='o9cq807eWLFtVvCrznpCX6OQmR5w@im.wechat'   # 刘子研（当前绑定号）
pdf='/Users/liuxinyuan/Desktop/Hermes输出-工作类/客户管理/拜访卡/上海万子健_访前作战卡_20261028.pdf'
caption='子研，上海万子健访前作战卡（2页）。重点看三件事：生殖道六重转产、HIV 冻干复测、RT-LAMP 送样。'

# 读取已有 context_token（只读长度，不打印内容）
ctx_path=os.path.join(PROFILE,'weixin/accounts/cc49fa005f05@im.bot.context-tokens.json')
ctx_data=json.load(open(ctx_path,encoding='utf-8')) if os.path.exists(ctx_path) else {}
context_token=ctx_data.get(to)

def ok(resp):
    if not isinstance(resp,dict): return False
    return (resp.get('ret') in (None,0)) and (resp.get('errcode') in (None,0))

async def send_text(s,text,client_id):
    return await wx._send_items(s,base_url=base_url,token=token,to=to,
        item_list=[{'type':wx.ITEM_TEXT,'text_item':{'text':text}}],
        context_token=context_token,client_id=client_id)

async def main():
    raw=Path(pdf).read_bytes()
    filekey=secrets.token_hex(16); aes_key=secrets.token_bytes(16)
    rawsize=len(raw); rawmd5=hashlib.md5(raw).hexdigest()
    filesize=((rawsize+16)//16)*16
    async with wx._new_session() as s:
        up=await wx._get_upload_url(s,base_url=base_url,token=token,to_user_id=to,
            media_type=wx.MEDIA_FILE,filekey=filekey,rawsize=rawsize,rawfilemd5=rawmd5,
            filesize=filesize,aeskey_hex=aes_key.hex())
        upload_param=str(up.get('upload_param') or '')
        upload_url=str(up.get('upload_full_url') or '') or (upload_param and (
            f"{cdn_base}/upload?encrypted_query_param={quote(upload_param,safe='')}&filekey={quote(filekey,safe='')}"))
        if not upload_url: raise RuntimeError('no upload url')
        ciphertext=wx._aes128_ecb_encrypt(raw,aes_key)
        enc=await wx._upload_ciphertext(s,ciphertext=ciphertext,upload_url=upload_url)
        item=wx._file_item(encrypt_query_param=enc,
            aes_key_for_api=base64.b64encode(aes_key.hex().encode('ascii')).decode('ascii'),
            ciphertext_size=len(ciphertext),plaintext_size=rawsize,
            filename=Path(pdf).name,rawfilemd5=rawmd5)
        # 先发文字说明，再发文件
        r1=await send_text(s,caption,f'hermes-wx-{secrets.token_hex(8)}')
        print('text',json.dumps(r1,ensure_ascii=False)[:300])
        r2=await wx._send_items(s,base_url=base_url,token=token,to=to,
            item_list=[item],context_token=context_token,client_id=f'hermes-wx-{secrets.token_hex(8)}')
        print('file',json.dumps(r2,ensure_ascii=False)[:300])
        # 本地留痕（直发不经过网关日志）
        outdir='/Users/liuxinyuan/Desktop/Hermes输出-工作类/团队共享'
        os.makedirs(outdir,exist_ok=True)
        stamp=time.strftime('%Y%m%d_%H%M%S')
        Path(os.path.join(outdir,f'_推送内容_上海万子健访前作战卡_{stamp}.txt')).write_text(
            f'收件人：刘子研（{to}）\n文件：{pdf}\n说明：{caption}\n发送时间：{stamp}\n方式：微信直发（不经过网关日志）\n',encoding='utf-8')
        Path(os.path.join(outdir,f'_推送回执_上海万子健访前作战卡_{stamp}.json')).write_text(
            json.dumps({'to':to,'file':pdf,'text_response':r1,'file_response':r2},ensure_ascii=False,indent=2),encoding='utf-8')
        print('saved receipt',stamp)
        return r1,r2

r1,r2=asyncio.run(main())
print('accepted',ok(r1) and ok(r2))
