#!/usr/bin/env python3
"""
手机号加密工具 — 与 Go 端 Encrypt 函数完全一致

Go 原始逻辑:
  func Encrypt(data string) string {
      key := "K1pNOZ5O5+ZqTPSHA2kzPdoNOMOGcv6g"
      encryptData := xxtea.Encrypt([]byte(data), []byte(key))
      n := base64.StdEncoding.EncodeToString(encryptData)
      n = strings.ReplaceAll(n, "+", "-")
      n = strings.ReplaceAll(n, "/", "_")
      n = strings.ReplaceAll(n, "=", ".")
      return n
  }

匹配方式: 加密明文手机号 → 与 bi_vala_app_account.tel_encrypt 比对 → 获取 account_id

MD5 加密: tel_encrypt → 解密为明文 → MD5 → 用于跨系统关联
"""
import xxtea
import base64
import hashlib

KEY = "K1pNOZ5O5+ZqTPSHA2kzPdoNOMOGcv6g"


def encrypt_phone(phone: str) -> str:
    """加密明文手机号，返回与数据库 tel_encrypt 字段一致的密文"""
    encrypted = xxtea.encrypt(phone.encode(), KEY.encode())
    result = base64.b64encode(encrypted).decode()
    result = result.replace("+", "-").replace("/", "_").replace("=", ".")
    return result


def encrypt_phones(phones: list[str]) -> dict[str, str]:
    """批量加密手机号，返回 {密文: 明文手机号} 映射"""
    return {encrypt_phone(p): p for p in phones}


def decrypt_phone(encrypted: str) -> str:
    """解密 tel_encrypt 还原明文手机号（仅用于验证）"""
    restored = encrypted.replace("-", "+").replace("_", "/").replace(".", "=")
    decrypted = xxtea.decrypt(base64.b64decode(restored), KEY.encode())
    return decrypted.decode()


def phone_md5(phone: str) -> str:
    """明文手机号 → MD5（32位小写十六进制）"""
    return hashlib.md5(phone.encode()).hexdigest()


def tel_encrypt_to_md5(tel_encrypt: str) -> str:
    """tel_encrypt 密文 → 解密 → MD5（一步到位）"""
    phone = decrypt_phone(tel_encrypt)
    return phone_md5(phone)


if __name__ == "__main__":
    # 自测
    test_phones = ["13800138000", "15912345678", "18888888888"]
    for p in test_phones:
        enc = encrypt_phone(p)
        dec = decrypt_phone(enc)
        md5 = phone_md5(p)
        status = "✓" if dec == p else "✗"
        print(f"{p} → {enc} → {dec} → MD5:{md5} {status}")
