"""锦鲤掌柜 · 卡密推送示例（Python 3.8+，pip install cryptography requests）
用法：
  export JL_TOKEN=jlk_xxx          # 插件「更多 / 开发者」里生成的令牌
  python push.py 豆包月卡 cards.txt  # 一行一条卡密
卡密在你电脑上用仓库公钥加密后才发出，服务器只存密文；插件在线时自动取走、解密入库。"""
import base64, json, os, sys
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes, serialization

API = os.environ.get("JL_API", "https://yzg-relay.aiyuan.dpdns.org")
TOKEN = os.environ["JL_TOKEN"]
H = {"Authorization": "Bearer " + TOKEN, "Content-Type": "application/json"}
b64u = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=").decode()
unb64u = lambda s: base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def seal(pub_raw: bytes, text: str) -> str:
    pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), pub_raw)
    eph = ec.generate_private_key(ec.SECP256R1())
    eph_raw = eph.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint)
    key = HKDF(hashes.SHA256(), 32, salt=eph_raw, info=b"jinli-stock-v1").derive(eph.exchange(ec.ECDH(), pub))
    iv = os.urandom(12)
    return "v1.%s.%s.%s" % (b64u(eph_raw), b64u(iv), b64u(AESGCM(key).encrypt(iv, text.encode(), None)))

def push(kind: str, cards: list, ref: str = None) -> list:
    import requests
    pub = unb64u(requests.get(API + "/v1/stock/status", headers=H, timeout=15).json()["pub"])
    out = []
    for i in range(0, len(cards), 500):                      # 单批最多 500 条
        r = requests.post(API + "/v1/stock/push", headers=H, timeout=30,
                          data=json.dumps({"kind": kind, "ref": ref, "items": [seal(pub, c) for c in cards[i:i + 500]]}))
        j = r.json()
        if not j.get("ok"): raise SystemExit("推送失败：%s %s" % (j.get("error"), j.get("msg")))
        out.append(j["batch"])
    return out

if __name__ == "__main__":
    import requests
    kind, path = sys.argv[1], sys.argv[2]
    cards = [l.strip() for l in open(path, encoding="utf-8") if l.strip()]
    print("已推送", len(cards), "条，批次", push(kind, cards))
    print("库存", requests.get(API + "/v1/stock/status", headers=H, timeout=15).json())
