import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Doubao Mini Program HTTP signing and response decryption.
 *
 * <p>Protocol-compatible with Ocean cloud-secret-sdk v1.6.11. Unencrypted
 * PKCS#8 (BEGIN PRIVATE KEY) and SEC1 (BEGIN EC PRIVATE KEY) P-256 keys are
 * accepted. Production verification should pass a NonceVerifier backed by
 * Ocean VerifyNonce or an equivalent shared replay-prevention service.</p>
 */
public final class DoubaoSecret {
    public static final String SIGN_ALGORITHM = "ECDSA_SHA256";
    public static final String VERSION = "1";
    public static final String AUTH_HEADER_NAME = "x-doubao-authorization";

    private static final int NONCE_BYTES = 12;
    private static final int TLV_HEADER_BYTES = 6;
    private static final int TLV_VERSION = 0x0001;
    private static final int TLV_EPHEMERAL_PUBLIC_KEY = 0x0002;
    private static final int TLV_DATA_KEY_CIPHER = 0x0003;
    private static final int TLV_DATA_CIPHER = 0x0004;
    private static final int AES_GCM_IV_BYTES = 12;
    private static final int AES_GCM_TAG_BITS = 128;

    private static final Set<String> SUPPORTED_METHODS = new HashSet<>(Arrays.asList(
        "GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE"
    ));
    private static final Pattern AUTH_PART = Pattern.compile(
        "([A-Za-z0-9_]+)=\"([A-Za-z0-9+/=_-]*)\""
    );
    private static final Pattern SERIAL = Pattern.compile("[0-9a-f]+");
    private static final Pattern NONCE = Pattern.compile("[A-Za-z0-9_-]{16}");
    private static final char[] HEX = "0123456789abcdef".toCharArray();
    private static final SecureRandom RANDOM = new SecureRandom();

    private DoubaoSecret() {}

    @FunctionalInterface
    public interface NonceVerifier {
        boolean verify(String nonce, long timestamp) throws Exception;
    }

    public static String sign(
        String method,
        String path,
        String query,
        String body,
        String privateKeyPem,
        String certSerial,
        Long timestampSeconds,
        String nonce
    ) throws Exception {
        long timestamp = timestampSeconds == null ? Instant.now().getEpochSecond() : timestampSeconds;
        String nonceValue = nonce == null ? generateNonce() : nonce;
        validateSigningNonce(nonceValue);
        certSerial = certSerial == null ? "" : certSerial.toLowerCase(java.util.Locale.ROOT);
        validateCertSerial(certSerial);

        ECPrivateKey privateKey = loadPrivateKey(privateKeyPem);
        String signContent = buildSignContent(
            method, path, nullToEmpty(query), nullToEmpty(body), timestamp, nonceValue
        );
        byte[] digest = sha256(signContent.getBytes(StandardCharsets.UTF_8));
        Signature signer = Signature.getInstance("NONEwithECDSA");
        signer.initSign(privateKey, RANDOM);
        signer.update(digest);
        String signature = Base64.getUrlEncoder().encodeToString(signer.sign());

        return String.format(
            "algorithm=\"%s\",version=\"%s\",signature=\"%s\",cert_serial=\"%s\",nonce=\"%s\",timestamp=\"%d\"",
            SIGN_ALGORITHM, VERSION, signature, certSerial, nonceValue, timestamp
        );
    }

    public static boolean verifySign(
        String method,
        String path,
        String query,
        String body,
        String authorizationHeader,
        String certificatePem,
        NonceVerifier nonceVerifier
    ) throws Exception {
        Map<String, String> auth = parseAuthorizationHeader(authorizationHeader);
        long timestamp;
        try {
            timestamp = Long.parseLong(auth.get("timestamp"));
        } catch (NumberFormatException exception) {
            throw new IllegalArgumentException("authorization timestamp must be an integer", exception);
        }
        if (timestamp <= 0) {
            throw new IllegalArgumentException("authorization timestamp must be positive");
        }

        X509Certificate certificate = loadCertificate(certificatePem);
        if (!auth.get("cert_serial").equalsIgnoreCase(certificateSerial(certificate))) {
            throw new IllegalArgumentException("authorization cert_serial does not match certificate");
        }
        if (!(certificate.getPublicKey() instanceof ECPublicKey)) {
            throw new IllegalArgumentException("EC public key required in certificate");
        }

        String signContent = buildSignContent(
            method, path, nullToEmpty(query), nullToEmpty(body), timestamp, auth.get("nonce")
        );
        byte[] digest = sha256(signContent.getBytes(StandardCharsets.UTF_8));
        byte[] signatureBytes;
        try {
            if (auth.get("signature").length() % 4 != 0) {
                throw new IllegalArgumentException("signature must use padded Base64URL");
            }
            signatureBytes = Base64.getUrlDecoder().decode(auth.get("signature"));
        } catch (IllegalArgumentException exception) {
            throw new IllegalArgumentException("invalid padded Base64URL signature", exception);
        }
        Signature verifier = Signature.getInstance("NONEwithECDSA");
        verifier.initVerify(certificate.getPublicKey());
        verifier.update(digest);
        if (!verifier.verify(signatureBytes)) {
            return false;
        }
        return nonceVerifier == null || nonceVerifier.verify(auth.get("nonce"), timestamp);
    }

    public static String decrypt(String cipherDataBase64Url, String privateKeyPem) throws Exception {
        if (cipherDataBase64Url == null || cipherDataBase64Url.isEmpty()) {
            throw new IllegalArgumentException("cipherDataBase64Url is required");
        }
        byte[] blob = decodeBase64UrlLenient(cipherDataBase64Url);
        ByteBuffer buffer = ByteBuffer.wrap(blob).order(ByteOrder.BIG_ENDIAN);
        Map<Integer, byte[]> fields = new HashMap<>();
        while (buffer.hasRemaining()) {
            if (buffer.remaining() < TLV_HEADER_BYTES) {
                throw new IllegalArgumentException("invalid TLV header");
            }
            int type = Short.toUnsignedInt(buffer.getShort());
            long unsignedLength = Integer.toUnsignedLong(buffer.getInt());
            if (unsignedLength > buffer.remaining() || unsignedLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("invalid TLV length");
            }
            byte[] value = new byte[(int) unsignedLength];
            buffer.get(value);
            fields.put(type, value);
        }

        byte[] version = fields.get(TLV_VERSION);
        if (version == null || version.length != 2
            || Short.toUnsignedInt(ByteBuffer.wrap(version).order(ByteOrder.BIG_ENDIAN).getShort()) != 1) {
            throw new IllegalArgumentException("missing or unsupported TLV version");
        }
        byte[] ephemeral = fields.get(TLV_EPHEMERAL_PUBLIC_KEY);
        byte[] dataKeyCipher = fields.get(TLV_DATA_KEY_CIPHER);
        byte[] dataCipher = fields.get(TLV_DATA_CIPHER);
        if (ephemeral == null || dataKeyCipher == null || dataCipher == null) {
            throw new IllegalArgumentException("missing required TLV fields");
        }
        if (ephemeral.length != 65 || ephemeral[0] != 0x04) {
            throw new IllegalArgumentException("invalid ephemeral public key");
        }

        ECPrivateKey privateKey = loadPrivateKey(privateKeyPem);
        int coordinateBytes = 32;
        BigInteger x = new BigInteger(1, Arrays.copyOfRange(ephemeral, 1, 1 + coordinateBytes));
        BigInteger y = new BigInteger(1, Arrays.copyOfRange(ephemeral, 1 + coordinateBytes, 65));
        ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(
            new ECPoint(x, y), privateKey.getParams()
        );
        ECPublicKey ephemeralKey = (ECPublicKey) KeyFactory.getInstance("EC").generatePublic(publicKeySpec);

        KeyAgreement agreement = KeyAgreement.getInstance("ECDH");
        agreement.init(privateKey);
        agreement.doPhase(ephemeralKey, true);
        byte[] sharedSecret = normalizeTo32Bytes(agreement.generateSecret());
        byte[] kek = sha256(sharedSecret);
        byte[] dataKey = aesGcmDecrypt(kek, dataKeyCipher);
        byte[] plaintext = aesGcmDecrypt(dataKey, dataCipher);
        return new String(plaintext, StandardCharsets.UTF_8);
    }

    static String buildCanonicalQuery(String query) throws Exception {
        if (query == null || query.isEmpty()) {
            return "";
        }
        if (query.indexOf(';') >= 0) {
            throw new IllegalArgumentException("invalid query string: unescaped semicolon");
        }
        List<String[]> pairs = new ArrayList<>();
        for (String pair : query.split("&", -1)) {
            if (pair.isEmpty()) {
                continue;
            }
            int equals = pair.indexOf('=');
            String rawKey = equals < 0 ? pair : pair.substring(0, equals);
            String rawValue = equals < 0 ? "" : pair.substring(equals + 1);
            String key = URLDecoder.decode(rawKey, StandardCharsets.UTF_8.name());
            String value = URLDecoder.decode(rawValue, StandardCharsets.UTF_8.name());
            pairs.add(new String[] {key, value});
        }
        pairs.sort((left, right) -> {
            int keyOrder = compareUtf8(left[0], right[0]);
            return keyOrder != 0 ? keyOrder : compareUtf8(left[1], right[1]);
        });
        StringBuilder result = new StringBuilder();
        for (String[] pair : pairs) {
            if (result.length() > 0) {
                result.append('&');
            }
            result.append(pair[0]).append('=').append(pair[1]);
        }
        return result.toString();
    }

    private static String buildSignContent(
        String method, String path, String query, String body, long timestamp, String nonce
    ) throws Exception {
        validateMethodAndPath(method, path);
        if (timestamp <= 0) {
            throw new IllegalArgumentException("timestamp must be positive");
        }
        validateNonce(nonce);
        String canonicalQuery = buildCanonicalQuery(query);
        String bodyHash = toHex(sha256(body.getBytes(StandardCharsets.UTF_8)));
        return method + "\n" + path + "\n" + canonicalQuery + "\n"
            + bodyHash + "\n" + timestamp + "\n" + nonce;
    }

    private static Map<String, String> parseAuthorizationHeader(String header) {
        if (header == null || header.isEmpty()) {
            throw new IllegalArgumentException("x-doubao-authorization is required");
        }
        Map<String, String> fields = new HashMap<>();
        for (String rawPart : header.split(",", -1)) {
            Matcher matcher = AUTH_PART.matcher(rawPart.trim());
            if (!matcher.matches()) {
                throw new IllegalArgumentException("invalid x-doubao-authorization format");
            }
            if (fields.putIfAbsent(matcher.group(1), matcher.group(2)) != null) {
                throw new IllegalArgumentException("duplicate authorization field: " + matcher.group(1));
            }
        }
        for (String key : Arrays.asList(
            "algorithm", "version", "signature", "cert_serial", "nonce", "timestamp"
        )) {
            if (!fields.containsKey(key) || fields.get(key).isEmpty()) {
                throw new IllegalArgumentException("missing authorization field: " + key);
            }
        }
        if (!SIGN_ALGORITHM.equals(fields.get("algorithm")) || !VERSION.equals(fields.get("version"))) {
            throw new IllegalArgumentException("unsupported authorization algorithm or version");
        }
        validateVerificationCertSerial(fields.get("cert_serial"));
        validateNonce(fields.get("nonce"));
        return fields;
    }

    private static void validateMethodAndPath(String method, String path) throws Exception {
        if (!SUPPORTED_METHODS.contains(method)) {
            throw new IllegalArgumentException("unsupported HTTP method; method must be uppercase: " + method);
        }
        if (path == null || !path.startsWith("/")) {
            throw new IllegalArgumentException("request path must start with '/'");
        }
        URI parsed = new URI(path);
        if (parsed.getScheme() != null || parsed.getAuthority() != null
            || parsed.getRawQuery() != null || parsed.getRawFragment() != null
            || !path.equals(parsed.getPath())) {
            throw new IllegalArgumentException("invalid request path: " + path);
        }
    }

    private static ECPrivateKey loadPrivateKey(String pem) throws Exception {
        byte[] der;
        if (pem != null && pem.contains("-----BEGIN PRIVATE KEY-----")) {
            der = decodePem(pem, "PRIVATE KEY");
        } else {
            der = wrapSec1P256AsPkcs8(decodePem(pem, "EC PRIVATE KEY"));
        }
        PrivateKey key = KeyFactory.getInstance("EC").generatePrivate(new PKCS8EncodedKeySpec(der));
        if (!(key instanceof ECPrivateKey)) {
            throw new IllegalArgumentException("P-256 EC private key required");
        }
        ECPrivateKey ecKey = (ECPrivateKey) key;
        if (ecKey.getParams().getOrder().bitLength() != 256) {
            throw new IllegalArgumentException("P-256 EC private key required");
        }
        return ecKey;
    }

    private static byte[] wrapSec1P256AsPkcs8(byte[] sec1) {
        byte[] algorithmIdentifier = new byte[] {
            0x30, 0x13,
            0x06, 0x07, 0x2a, (byte) 0x86, 0x48, (byte) 0xce, 0x3d, 0x02, 0x01,
            0x06, 0x08, 0x2a, (byte) 0x86, 0x48, (byte) 0xce, 0x3d, 0x03, 0x01, 0x07
        };
        ByteArrayOutputStream content = new ByteArrayOutputStream();
        content.write(0x02); // version INTEGER 0
        content.write(0x01);
        content.write(0x00);
        content.write(algorithmIdentifier, 0, algorithmIdentifier.length);
        content.write(0x04); // privateKey OCTET STRING
        writeDerLength(content, sec1.length);
        content.write(sec1, 0, sec1.length);

        byte[] body = content.toByteArray();
        ByteArrayOutputStream sequence = new ByteArrayOutputStream();
        sequence.write(0x30);
        writeDerLength(sequence, body.length);
        sequence.write(body, 0, body.length);
        return sequence.toByteArray();
    }

    private static void writeDerLength(ByteArrayOutputStream output, int length) {
        if (length < 0x80) {
            output.write(length);
            return;
        }
        int bytes = 0;
        int remaining = length;
        while (remaining > 0) {
            bytes++;
            remaining >>>= 8;
        }
        output.write(0x80 | bytes);
        for (int shift = (bytes - 1) * 8; shift >= 0; shift -= 8) {
            output.write((length >>> shift) & 0xff);
        }
    }

    private static X509Certificate loadCertificate(String pem) throws Exception {
        byte[] der = decodePem(pem, "CERTIFICATE");
        return (X509Certificate) CertificateFactory.getInstance("X.509")
            .generateCertificate(new ByteArrayInputStream(der));
    }

    private static byte[] decodePem(String pem, String type) {
        if (pem == null) {
            throw new IllegalArgumentException("PEM " + type + " is required");
        }
        String begin = "-----BEGIN " + type + "-----";
        String end = "-----END " + type + "-----";
        int start = pem.indexOf(begin);
        int finish = pem.indexOf(end);
        if (start < 0 || finish <= start) {
            throw new IllegalArgumentException("invalid PEM " + type);
        }
        String encoded = pem.substring(start + begin.length(), finish).replaceAll("\\s", "");
        return Base64.getDecoder().decode(encoded);
    }

    private static String certificateSerial(X509Certificate certificate) {
        byte[] bytes = certificate.getSerialNumber().toByteArray();
        if (bytes.length > 1 && bytes[0] == 0) {
            bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
        }
        return toHex(bytes);
    }

    private static byte[] aesGcmDecrypt(byte[] key, byte[] cipherData) throws Exception {
        if (cipherData.length < AES_GCM_IV_BYTES + AES_GCM_TAG_BITS / 8) {
            throw new IllegalArgumentException("invalid AES-GCM data");
        }
        byte[] iv = Arrays.copyOfRange(cipherData, 0, AES_GCM_IV_BYTES);
        byte[] ciphertextAndTag = Arrays.copyOfRange(cipherData, AES_GCM_IV_BYTES, cipherData.length);
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(AES_GCM_TAG_BITS, iv));
        return cipher.doFinal(ciphertextAndTag);
    }

    private static byte[] normalizeTo32Bytes(byte[] value) {
        if (value.length == 32) {
            return value;
        }
        byte[] normalized = new byte[32];
        if (value.length > 32) {
            System.arraycopy(value, value.length - 32, normalized, 0, 32);
        } else {
            System.arraycopy(value, 0, normalized, 32 - value.length, value.length);
        }
        return normalized;
    }

    private static int compareUtf8(String left, String right) {
        byte[] a = left.getBytes(StandardCharsets.UTF_8);
        byte[] b = right.getBytes(StandardCharsets.UTF_8);
        int length = Math.min(a.length, b.length);
        for (int i = 0; i < length; i++) {
            int comparison = Integer.compare(Byte.toUnsignedInt(a[i]), Byte.toUnsignedInt(b[i]));
            if (comparison != 0) {
                return comparison;
            }
        }
        return Integer.compare(a.length, b.length);
    }

    private static byte[] decodeBase64UrlLenient(String value) {
        StringBuilder padded = new StringBuilder(value);
        while (padded.length() % 4 != 0) {
            padded.append('=');
        }
        return Base64.getUrlDecoder().decode(padded.toString());
    }

    private static byte[] sha256(byte[] value) throws Exception {
        return MessageDigest.getInstance("SHA-256").digest(value);
    }

    private static String toHex(byte[] value) {
        char[] output = new char[value.length * 2];
        for (int i = 0; i < value.length; i++) {
            int current = Byte.toUnsignedInt(value[i]);
            output[i * 2] = HEX[current >>> 4];
            output[i * 2 + 1] = HEX[current & 0x0f];
        }
        return new String(output);
    }

    private static String generateNonce() {
        byte[] bytes = new byte[NONCE_BYTES];
        RANDOM.nextBytes(bytes);
        return Base64.getUrlEncoder().encodeToString(bytes);
    }

    private static void validateNonce(String nonce) {
        if (nonce == null || !nonce.matches("[A-Za-z0-9_-]+")) {
            throw new IllegalArgumentException("nonce must be non-empty Base64URL text");
        }
    }

    private static void validateSigningNonce(String nonce) {
        if (nonce == null || !NONCE.matcher(nonce).matches()) {
            throw new IllegalArgumentException("signing nonce must be exactly 16 Base64URL characters");
        }
    }

    private static void validateCertSerial(String serial) {
        if (serial == null || serial.length() % 2 != 0 || !SERIAL.matcher(serial).matches()) {
            throw new IllegalArgumentException(
                "cert_serial must be non-empty, even-length lowercase hexadecimal"
            );
        }
    }

    private static void validateVerificationCertSerial(String serial) {
        if (serial == null || serial.length() % 2 != 0 || !serial.matches("[0-9a-fA-F]+")) {
            throw new IllegalArgumentException(
                "cert_serial must be non-empty, even-length hexadecimal"
            );
        }
    }

    private static String nullToEmpty(String value) {
        return value == null ? "" : value;
    }
}
