package com.srs.common.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.alibaba.fastjson2.JSON;

import java.io.ByteArrayOutputStream;
import java.security.interfaces.RSAPrivateKey;


import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
import java.time.Instant;
import java.util.*;
public class JwtUtil {
    private static final String COZE_APP_ID = "1113337098945";
    private static final String COZE_KID = "95GkNSb-eKeS34ADxQ1Ex4FJYaFylEUChe_rlyOolQ4";

    public static String generateJwt(String userId) throws Exception {
        Instant now = Instant.now();

        // 1. 构造 Payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("iat", now.getEpochSecond());
        payload.put("exp", now.plusSeconds(600).getEpochSecond());
        payload.put("jti", userId + "-" + UUID.randomUUID());
        payload.put("aud", "api.coze.cn");
        payload.put("iss", COZE_APP_ID);
        payload.put("session_name", userId);

        // session_context.device_info.device_id
        Map<String, Object> deviceInfo = new HashMap<>();
        deviceInfo.put("device_id", "device_" + userId);

        Map<String, Object> sessionContext = new HashMap<>();
        sessionContext.put("device_info", deviceInfo);

        payload.put("session_context", sessionContext);

        // 2. 构造 Header
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "RS256");
        header.put("typ", "JWT");
        header.put("kid", COZE_KID);

        // 3. 使用私钥签名
        PrivateKey privateKey = loadPrivateKeyFromPem("keys/private_key.pem");

        Algorithm algorithm = Algorithm.RSA256(null, (RSAPrivateKey) privateKey);
        return JWT.create()
                .withHeader(header)
                .withPayload(payload)
                .sign(algorithm);
    }

    // 加载私钥
    private static PrivateKey loadPrivateKeyFromPem(String pemPath) throws Exception {
        InputStream is = JwtUtil.class.getClassLoader().getResourceAsStream(pemPath);
        if (is == null) {
            throw new RuntimeException("无法加载私钥文件：" + pemPath);
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        String pem = new String(baos.toByteArray(), StandardCharsets.UTF_8)
                .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                .replaceAll("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s", "");

        byte[] keyBytes = Base64.getDecoder().decode(pem);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }
}
