#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""轮询已发出的微信绑定二维码状态；确认后写入账号文件（不打印 token）
用法：venv/bin/python 脚本/poll_weixin_qr.py   （读 /tmp/wx_qr_url.txt 里的 token）
输出：SCANNED / CONFIRMED account_id=... / EXPIRED / TIMEOUT（token 只打印长度）
"""
import asyncio, sys, os, json

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


async def main():
    from gateway.platforms.weixin import (_api_get, _new_session, save_weixin_account,
                                          EP_GET_QR_STATUS, ILINK_BASE_URL, QR_TIMEOUT_MS)
    lines = open('/tmp/wx_qr_url.txt', encoding='utf-8').read().split('\n')
    token = (lines[1] if len(lines) > 1 else '').strip()
    if not token:
        print('NO_TOKEN'); return 2
    base, last = ILINK_BASE_URL, ''
    async with _new_session() as s:
        for _ in range(900):                      # ~30 分钟上限（2s 间隔）
            try:
                r = await _api_get(s, base_url=base,
                                   endpoint=f"{EP_GET_QR_STATUS}?qrcode={token}",
                                   timeout_ms=QR_TIMEOUT_MS)
            except Exception:
                await asyncio.sleep(2); continue
            st = str(r.get('status') or 'wait')
            if st != last:
                print('status:', st, flush=True); last = st
            if st == 'scaned':
                print('SCANNED: 已扫码，请在微信里点确认', flush=True)
            elif st == 'scaned_but_redirect' and r.get('redirect_host'):
                base = 'https://' + str(r['redirect_host'])
            elif st == 'confirmed':
                creds = {'account_id': str(r.get('ilink_bot_id') or ''),
                         'token': str(r.get('bot_token') or ''),
                         'base_url': str(r.get('baseurl') or ILINK_BASE_URL),
                         'user_id': str(r.get('ilink_user_id') or '')}
                if not creds['account_id'] or not creds['token']:
                    print('CONFIRMED_BUT_INCOMPLETE'); return 3
                save_weixin_account(HERMES_HOME, **creds)
                json.dump({'account_id': creds['account_id'], 'user_id': creds['user_id'],
                           'base_url': creds['base_url']},
                          open('/tmp/wx_bind_result.json', 'w', encoding='utf-8'), ensure_ascii=False)
                print('CONFIRMED account_id=%s user_id=%s token_len=%d'
                      % (creds['account_id'], creds['user_id'], len(creds['token'])), flush=True)
                return 0
            elif st == 'expired':
                print('EXPIRED: 二维码已过期，需要重新生成', flush=True); return 4
            await asyncio.sleep(2)
    print('TIMEOUT'); return 5


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