#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""拉取微信 iLink 绑定二维码 → 渲染 PNG（供飞书发送）"""
import asyncio, sys, os

REPO = os.path.expanduser('~/.hermes/hermes-agent')
sys.path.insert(0, REPO)

async def main():
    from gateway.platforms.weixin import _fetch_qr, _new_session
    bot_type = sys.argv[1] if len(sys.argv) > 1 else '3'
    async with _new_session() as s:
        val, url = await _fetch_qr(s, bot_type)
    print('RAW_TOKEN_LEN:', len(val or ''))
    print('QR_URL:', url or '(空)')
    if not val and not url:
        print('!! 未取到二维码（接口未返回 qrcode）')
        return 2
    open('/tmp/wx_qr_url.txt', 'w', encoding='utf-8').write((url or '') + '\n' + (val or ''))
    import qrcode
    target = url or val
    qr = qrcode.QRCode(box_size=10, border=3, error_correction=qrcode.constants.ERROR_CORRECT_M)
    qr.add_data(target)
    qr.make(fit=True)
    img = qr.make_image(fill_color='black', back_color='white')
    img.save('/tmp/weixin_bind_qr.png')
    print('PNG:', '/tmp/weixin_bind_qr.png', os.path.getsize('/tmp/weixin_bind_qr.png'), 'bytes')
    return 0

sys.exit(asyncio.run(main()))
