#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""换绑落库：把新微信账号写入 ~/.hermes/.env 并重启网关
用法：venv/bin/python 脚本/apply_weixin_bind.py
前置：/tmp/wx_bind_result.json（由 weixin_qr_watch.py 在扫码确认后写出）+ 账号文件已由 save_weixin_account 落盘
不打印 token。
"""
import os, sys, json, re, shutil, subprocess, time

HERMES_HOME = os.path.expanduser('~/.hermes')
ENV = os.path.join(HERMES_HOME, '.env')
ACCOUNTS = os.path.join(HERMES_HOME, 'weixin', 'accounts')


def read_account(account_id):
    p = os.path.join(ACCOUNTS, '%s.json' % account_id)
    if not os.path.exists(p):
        return None
    d = json.load(open(p, encoding='utf-8'))
    tok = ''
    for k in ('token', 'bot_token', 'access_token', 'WEIXIN_TOKEN'):
        if d.get(k):
            tok = str(d[k]); break
    return {'path': p, 'token': tok, 'raw_keys': sorted(d.keys()), 'base_url': str(d.get('base_url') or '')}


def set_env(key, value):
    lines = open(ENV, encoding='utf-8').read().split('\n') if os.path.exists(ENV) else []
    pat = re.compile(r'^%s=' % re.escape(key))
    hit = False
    for i, l in enumerate(lines):
        if pat.match(l):
            lines[i] = '%s=%s' % (key, value); hit = True
    if not hit:
        lines.append('%s=%s' % (key, value))
    open(ENV, 'w', encoding='utf-8').write('\n'.join(lines))
    return hit


def main():
    res_path = '/tmp/wx_bind_result.json'
    if not os.path.exists(res_path):
        print('NO_RESULT_FILE: 还没有扫码确认结果'); return 2
    r = json.load(open(res_path, encoding='utf-8'))
    acc, uid, base = r.get('account_id', ''), r.get('user_id', ''), r.get('base_url', '')
    if not acc or not uid:
        print('INCOMPLETE_RESULT'); return 3
    acct = read_account(acc)
    if not acct or not acct['token']:
        print('NO_TOKEN_IN_ACCOUNT_FILE  account_id=%s path=%s' % (acc, acct['path'] if acct else '?')); return 4

    before = {}
    for k in ('WEIXIN_ACCOUNT_ID', 'WEIXIN_HOME_CHANNEL'):
        m = re.search(r'^%s=(.*)$' % k, open(ENV, encoding='utf-8').read(), re.M) if os.path.exists(ENV) else None
        before[k] = m.group(1).strip() if m else '(未设置)'
    bak = ENV + '.bak_swap_' + time.strftime('%Y%m%d_%H%M%S')
    shutil.copy2(ENV, bak)

    set_env('WEIXIN_ACCOUNT_ID', acc)
    set_env('WEIXIN_TOKEN', acct['token'])
    set_env('WEIXIN_BASE_URL', base or acct['base_url'] or 'https://ilinkai.weixin.qq.com')
    set_env('WEIXIN_HOME_CHANNEL', uid)
    print('OLD: ACCOUNT_ID=%s  HOME_CHANNEL=%s' % (before['WEIXIN_ACCOUNT_ID'], before['WEIXIN_HOME_CHANNEL']))
    print('NEW: ACCOUNT_ID=%s  HOME_CHANNEL=%s  token_len=%d' % (acc, uid, len(acct['token'])))
    print('BACKUP:', bak)

    print('--- 重启网关 ---')
    p = subprocess.run(['hermes', 'gateway', 'restart'], capture_output=True, text=True, timeout=180)
    print((p.stdout or '')[-800:])
    if p.returncode != 0:
        print('RESTART_RC=%d stderr=%s' % (p.returncode, (p.stderr or '')[-400:]))
    time.sleep(8)
    s = subprocess.run(['hermes', 'gateway', 'status'], capture_output=True, text=True, timeout=120)
    out = s.stdout or ''
    for line in out.split('\n'):
        if re.search(r'gateway|weixin|Weixin|PID|✓|✗', line):
            print('  ', line.strip())
    return 0


sys.exit(main())
