package com.ruoyi.aicall.sign;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.UUID;

public final class KeyPairGenerator {

    // 全局固定种子（只在服务端保存，不泄露）
    private static final String SERVER_SEED = "ChangeMe_To_A_Strong_Random_String_At_Least_32_Byte";

    /**
     * 生成新的 AppKey / AppSecret
     *
     * @return [0]=AppKey , [1]=AppSecret
     */
    public static String[] generate() {
        // 1. AppKey：去掉中划线的 UUID，长度 32
        String appKey = UUID.randomUUID().toString().replace("-", "");

        // 2. AppSecret：HmacSHA256(AppKey, SERVER_SEED) -> Base64
        String appSecret = hmacSha256Base64(appKey, SERVER_SEED);

        return new String[]{appKey, appSecret};
    }

    private static String hmacSha256Base64(String message, String secret) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] hash = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(hash);
        } catch (Exception e) {
            throw new RuntimeException("HmacSHA256 error", e);
        }
    }

    protected static String getSecretByAppKey(String appKey) {
        // HmacSHA256(AppKey, SERVER_SEED) -> Base64
        return hmacSha256Base64(appKey, SERVER_SEED);
    }

    // Demo
    public static void main(String[] args) {
        String[] pair = generate();
        System.out.println("AppKey  : " + pair[0]);
        System.out.println("AppSecret: " + pair[1]);

        System.out.println(getSecretByAppKey("AK_123456"));
        System.out.println(getSecretByAppKey("AK_123456"));
        System.out.println(getSecretByAppKey("AK_123456"));
        System.out.println(getSecretByAppKey("AK_123456"));
    }
}
