# -*- coding: utf-8 -*-
"""把四张按套餐的收款码写进 data/pay.json 的 qrcodes（键 = planId）。

服务器上只有 python3，没有 node，所以这里用 python 写。
用法：LIC_ROOT=/opt/hxjc-lic python3 _setqrcodes.py
"""
import json
import os
import sys

ROOT = os.environ.get('LIC_ROOT') or '/opt/hxjc-lic'
CONF = os.path.join(ROOT, 'data', 'pay.json')

MAP = [
    ('w1', 'qr-w1.jpg', '周卡 7 元'),
    ('m1', 'qr-m1.jpg', '月卡 24 元'),
    ('m3', 'qr-m3.jpg', '季卡 63 元'),
    ('m12', 'qr-m12.jpg', '年卡 219 元'),
]


def main():
    try:
        with open(CONF, 'rb') as f:
            raw = f.read()
        if raw[:3] == b'\xef\xbb\xbf':
            raw = raw[3:]
        cfg = json.loads(raw.decode('utf-8'))
    except Exception as e:
        print('读不到 %s：%s' % (CONF, e))
        return 1

    qr = cfg.get('qrcodes')
    if not isinstance(qr, dict):
        qr = {}
        cfg['qrcodes'] = qr

    n = 0
    for pid, fn, note in MAP:
        fp = os.path.join(ROOT, fn)
        if not os.path.exists(fp):
            print('[跳过] %s 不存在（%s）' % (fn, note))
            continue
        with open(fp, 'rb') as f:
            head = f.read(4)
        is_jpg = head[:2] == b'\xff\xd8'
        is_png = head[:4] == b'\x89PNG'
        if not (is_jpg or is_png):
            print('[跳过] %s 不是有效图片' % fn)
            continue
        size = os.path.getsize(fp)
        qr[pid] = fn
        n += 1
        print('[设置] %-4s -> %-12s (%s, %dKB)' % (pid, fn, note, round(size / 1024.0)))

    if not cfg.get('payTip'):
        cfg['payTip'] = '扫码付款后回来点「我已付款」，管理员核对到账后为你会开通。'

    with open(CONF, 'w') as f:
        json.dump(cfg, f, ensure_ascii=False, indent=2)
    print('\n已写 %s，共设 %d 个套餐码' % (CONF, n))
    print('qrcodes = %s' % json.dumps(qr, ensure_ascii=False))
    return 0


if __name__ == '__main__':
    sys.exit(main())