package doubao_secret

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"encoding/base64"
	"encoding/binary"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"fmt"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"
)

const (
	SignAlgorithm = "ECDSA_SHA256"
	Version       = "1"

	AuthFieldSignature  = "signature"
	AuthFieldNonce      = "nonce"
	AuthFieldTimestamp  = "timestamp"
	AuthFieldCertSerial = "cert_serial"
	AuthHeaderFormat    = `algorithm="%s",version="%s",signature="%s",cert_serial="%s",nonce="%s",timestamp="%d"`

	// Ocean SDK v1.6.11 generates 12 random bytes, whose padded Base64URL
	// representation is exactly 16 characters.
	NonceBytes = 12

	// TLV
	TlvTypeBytes             = 2
	TlvLengthBytes           = 4
	TlvHeaderBytes           = TlvTypeBytes + TlvLengthBytes
	TlvVersionValueBytes     = 2
	SupportedTlvVersionValue = 1

	// EC point
	EcPointPrefixUncompressed = 0x04
	EcCoordBytes              = 32
	EcPointUncompressedBytes  = 1 + (EcCoordBytes * 2) // 65

	// AES-GCM
	AesGcmIvBytes  = 12
	AesGcmTagBytes = 16

	// TLV types
	TlvVersion         uint16 = 0x0001
	TlvEphemeralPubKey uint16 = 0x0002
	TlvDataKeyCipher   uint16 = 0x0003
	TlvDataCipher      uint16 = 0x0004
)

var supportedMethods = map[string]struct{}{
	"GET": {}, "HEAD": {}, "POST": {}, "PUT": {}, "PATCH": {},
	"DELETE": {}, "CONNECT": {}, "OPTIONS": {}, "TRACE": {},
}

// VerifySign 验证 Doubao 请求签名
// method: HTTP 方法, 如 "POST"
// path: 请求路径, 如 "/api/v1/endpoint"
// query: 请求参数字符串
// body: 请求体内容
// daobaoAuthorizationHeader: Header 中的 x-doubao-authorization 字段
// pemCert: X.509 PEM 证书
func VerifySign(method, path, query, body, daobaoAuthorizationHeader, pemCert string, debugPrintSignContent ...bool) (bool, error) {
	auth, err := parseAuthorizationHeader(daobaoAuthorizationHeader)
	if err != nil {
		return false, err
	}

	pubKey, certSerial, err := getPublicKeyAndSerialFromCert(pemCert)
	if err != nil {
		return false, err
	}
	if !strings.EqualFold(auth[AuthFieldCertSerial], certSerial) {
		return false, errors.New("authorization cert_serial does not match certificate")
	}

	signature, err := base64.URLEncoding.DecodeString(auth[AuthFieldSignature])
	if err != nil {
		return false, fmt.Errorf("decode authorization signature: %w", err)
	}

	timestamp, err := strconv.ParseInt(auth[AuthFieldTimestamp], 10, 64)
	if err != nil || timestamp <= 0 {
		return false, errors.New("authorization timestamp must be a positive integer")
	}
	signContent, err := buildSignContent(method, path, query, body, timestamp, auth[AuthFieldNonce])
	if err != nil {
		return false, err
	}
	if len(debugPrintSignContent) > 0 && debugPrintSignContent[0] {
		fmt.Println(signContent)
	}

	digest := sha256Bytes([]byte(signContent))
	return ecdsa.VerifyASN1(pubKey, digest, signature), nil
}

// Sign 生成 Doubao 请求的授权头字符串
// timestampSeconds 为 nil 时默认使用当前时间戳, nonce 为 nil 时默认随机生成
func Sign(method, path, query, body, pemEcPrivateKey, certSerial string, timestampSeconds *int64, nonce *string, debugPrintSignContent ...bool) (string, error) {
	var timestamp int64
	if timestampSeconds != nil {
		timestamp = *timestampSeconds
	} else {
		timestamp = time.Now().Unix()
	}

	var nonceVal string
	if nonce != nil && *nonce != "" {
		nonceVal = *nonce
	} else {
		n, err := generateNonce()
		if err != nil {
			return "", err
		}
		nonceVal = n
	}
	if err := validateSigningNonce(nonceVal); err != nil {
		return "", err
	}
	certSerial = strings.ToLower(certSerial)
	if err := validateCertSerial(certSerial); err != nil {
		return "", err
	}

	privKey, err := getEcPrivateKeyFromPem(pemEcPrivateKey)
	if err != nil {
		return "", err
	}

	signContent, err := buildSignContent(method, path, query, body, timestamp, nonceVal)
	if err != nil {
		return "", err
	}
	if len(debugPrintSignContent) > 0 && debugPrintSignContent[0] {
		fmt.Println(signContent)
	}

	digest := sha256Bytes([]byte(signContent))
	// Golang 默认生成 ASN.1 (DER) 格式签名
	sigDer, err := ecdsa.SignASN1(rand.Reader, privKey, digest)
	if err != nil {
		return "", err
	}

	signatureB64Url := base64.URLEncoding.EncodeToString(sigDer)

	header := fmt.Sprintf(AuthHeaderFormat, SignAlgorithm, Version, signatureB64Url, certSerial, nonceVal, timestamp)
	return header, nil
}

// Decrypt 解密 Doubao 返回密文 (TLV + ECDH + AES-GCM)
func Decrypt(cipherDataB64Url, pemEcPrivateKey string) (string, error) {
	if cipherDataB64Url == "" {
		return "", errors.New("cipherDataBase64Url is required")
	}
	if pemEcPrivateKey == "" {
		return "", errors.New("pemEcPrivateKey is required")
	}

	blob, err := b64UrlDecodeLenient(cipherDataB64Url)
	if err != nil {
		return "", err
	}

	var versionBytes, ephPubBytes, dataKeyCipher, dataCipher []byte

	offset := 0
	n := len(blob)
	for offset < n {
		if n-offset < TlvHeaderBytes {
			return "", errors.New("invalid TLV")
		}
		t := binary.BigEndian.Uint16(blob[offset : offset+2])
		offset += 2
		length := int(binary.BigEndian.Uint32(blob[offset : offset+4]))
		offset += 4

		if length < 0 || n-offset < length {
			return "", errors.New("invalid TLV")
		}
		value := blob[offset : offset+length]
		offset += length

		switch t {
		case TlvVersion:
			versionBytes = value
		case TlvEphemeralPubKey:
			ephPubBytes = value
		case TlvDataKeyCipher:
			dataKeyCipher = value
		case TlvDataCipher:
			dataCipher = value
		}
	}

	if len(versionBytes) != TlvVersionValueBytes {
		return "", errors.New("missing or invalid TLV version")
	}
	version := binary.BigEndian.Uint16(versionBytes)
	if version != SupportedTlvVersionValue {
		return "", fmt.Errorf("unsupported version: %d", version)
	}

	if len(ephPubBytes) == 0 || len(dataKeyCipher) == 0 || len(dataCipher) == 0 {
		return "", errors.New("missing required TLV fields")
	}

	privKey, err := getEcPrivateKeyFromPem(pemEcPrivateKey)
	if err != nil {
		return "", err
	}

	ephPubKey, err := buildEcPublicKey(ephPubBytes)
	if err != nil {
		return "", err
	}

	// ECDH key exchange - X 坐标即为 shared secret
	curve := elliptic.P256()
	x, _ := curve.ScalarMult(ephPubKey.X, ephPubKey.Y, privKey.D.Bytes())
	if x == nil {
		return "", errors.New("failed to generate shared secret")
	}

	// 格式化 shared secret 为 32 字节 (如果需要则前补零)
	sharedSecret := make([]byte, 32)
	xBytes := x.Bytes()
	copy(sharedSecret[32-len(xBytes):], xBytes)

	// KEK (AES-256 需要 32 字节)
	hash := sha256.Sum256(sharedSecret)
	kek := hash[:]

	dataKey, err := aesGcmDecrypt(kek, dataKeyCipher)
	if err != nil {
		return "", err
	}

	plaintext, err := aesGcmDecrypt(dataKey, dataCipher)
	if err != nil {
		return "", err
	}

	return string(plaintext), nil
}

// Helpers
func parseAuthorizationHeader(header string) (map[string]string, error) {
	if header == "" {
		return nil, errors.New("x-doubao-authorization is required")
	}
	fields := make(map[string]string)
	for _, part := range strings.Split(header, ",") {
		key, quotedValue, ok := strings.Cut(strings.TrimSpace(part), "=")
		if !ok || len(quotedValue) < 2 || quotedValue[0] != '"' || quotedValue[len(quotedValue)-1] != '"' {
			return nil, errors.New("invalid x-doubao-authorization format")
		}
		if _, exists := fields[key]; exists {
			return nil, fmt.Errorf("duplicate authorization field %q", key)
		}
		fields[key] = quotedValue[1 : len(quotedValue)-1]
	}
	for _, key := range []string{"algorithm", "version", AuthFieldSignature, AuthFieldCertSerial, AuthFieldNonce, AuthFieldTimestamp} {
		if fields[key] == "" {
			return nil, fmt.Errorf("missing authorization field %q", key)
		}
	}
	if fields["algorithm"] != SignAlgorithm || fields["version"] != Version {
		return nil, errors.New("unsupported authorization algorithm or version")
	}
	if err := validateNonce(fields[AuthFieldNonce]); err != nil {
		return nil, err
	}
	if err := validateVerificationCertSerial(fields[AuthFieldCertSerial]); err != nil {
		return nil, err
	}
	return fields, nil
}

func buildCanonicalQuery(query string) (string, error) {
	if query == "" {
		return "", nil
	}
	values, err := url.ParseQuery(query)
	if err != nil {
		return "", fmt.Errorf("invalid query string: %w", err)
	}
	keys := make([]string, 0, len(values))
	for key := range values {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	var result []string
	for _, key := range keys {
		vals := values[key]
		sort.Strings(vals)
		for _, value := range vals {
			result = append(result, key+"="+value)
		}
	}
	return strings.Join(result, "&"), nil
}

func buildSignContent(method, path, query, body string, timestamp int64, nonce string) (string, error) {
	if _, ok := supportedMethods[method]; !ok {
		return "", fmt.Errorf("unsupported HTTP method %q; method must be uppercase", method)
	}
	parsedPath, err := url.ParseRequestURI(path)
	if err != nil || parsedPath.Path != path || !strings.HasPrefix(path, "/") {
		return "", fmt.Errorf("invalid request path %q", path)
	}
	if timestamp <= 0 {
		return "", errors.New("timestamp must be positive")
	}
	if err := validateNonce(nonce); err != nil {
		return "", err
	}
	canonicalQuery, err := buildCanonicalQuery(query)
	if err != nil {
		return "", err
	}
	bodyHash := sha256.Sum256([]byte(body))
	bodySha256Hex := fmt.Sprintf("%x", bodyHash)
	return fmt.Sprintf("%s\n%s\n%s\n%s\n%d\n%s", method, path, canonicalQuery, bodySha256Hex, timestamp, nonce), nil
}

func sha256Bytes(data []byte) []byte {
	hash := sha256.Sum256(data)
	return hash[:]
}

func aesGcmDecrypt(key, cipherData []byte) ([]byte, error) {
	if len(cipherData) < AesGcmIvBytes+AesGcmTagBytes {
		return nil, errors.New("invalid AES-GCM data")
	}

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	aesgcm, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}

	iv := cipherData[:AesGcmIvBytes]
	ciphertext := cipherData[AesGcmIvBytes:]

	return aesgcm.Open(nil, iv, ciphertext, nil)
}

func getPublicKeyAndSerialFromCert(pemCert string) (*ecdsa.PublicKey, string, error) {
	block, _ := pem.Decode([]byte(pemCert))
	if block == nil || block.Type != "CERTIFICATE" {
		return nil, "", errors.New("failed to decode PEM cert")
	}

	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		return nil, "", err
	}

	pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey)
	if !ok {
		return nil, "", errors.New("EC public key required in certificate")
	}
	return pubKey, hex.EncodeToString(cert.SerialNumber.Bytes()), nil
}

func getEcPrivateKeyFromPem(pemStr string) (*ecdsa.PrivateKey, error) {
	block, _ := pem.Decode([]byte(pemStr))
	if block == nil {
		return nil, errors.New("failed to decode PEM private key")
	}

	// 尝试优先按照 EC 格式解析
	key, err := x509.ParseECPrivateKey(block.Bytes)
	if err != nil {
		// 如果失败，尝试通过 PKCS8 格式解析
		parsedKey, parseErr := x509.ParsePKCS8PrivateKey(block.Bytes)
		if parseErr != nil {
			return nil, errors.New("P-256 EC private key required")
		}
		var ok bool
		key, ok = parsedKey.(*ecdsa.PrivateKey)
		if !ok {
			return nil, errors.New("P-256 EC private key required")
		}
	}
	if key.Curve != elliptic.P256() {
		return nil, errors.New("P-256 EC private key required")
	}
	return key, nil
}

func buildEcPublicKey(pubBytes []byte) (*ecdsa.PublicKey, error) {
	if len(pubBytes) != EcPointUncompressedBytes || pubBytes[0] != EcPointPrefixUncompressed {
		return nil, errors.New("invalid ephemeral public key")
	}

	curve := elliptic.P256()
	x, y := elliptic.Unmarshal(curve, pubBytes)
	if x == nil {
		return nil, errors.New("invalid EC public key bytes")
	}

	return &ecdsa.PublicKey{Curve: curve, X: x, Y: y}, nil
}

func b64UrlDecodeLenient(s string) ([]byte, error) {
	// Base64Url 强行补齐 padding 以兼容
	if pad := len(s) % 4; pad > 0 {
		s += strings.Repeat("=", 4-pad)
	}
	return base64.URLEncoding.DecodeString(s)
}

func generateNonce() (string, error) {
	b := make([]byte, NonceBytes)
	_, err := rand.Read(b)
	if err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(b), nil
}

func validateNonce(nonce string) error {
	if nonce == "" {
		return errors.New("nonce must be non-empty Base64URL text")
	}
	for _, char := range nonce {
		if !((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') ||
			(char >= '0' && char <= '9') || char == '-' || char == '_') {
			return errors.New("nonce must be non-empty Base64URL text")
		}
	}
	return nil
}

func validateSigningNonce(nonce string) error {
	if len(nonce) != 16 {
		return errors.New("signing nonce must be exactly 16 Base64URL characters")
	}
	return validateNonce(nonce)
}

func validateCertSerial(certSerial string) error {
	if certSerial == "" || len(certSerial)%2 != 0 || strings.ToLower(certSerial) != certSerial {
		return errors.New("cert_serial must be non-empty, even-length lowercase hexadecimal")
	}
	if _, err := hex.DecodeString(certSerial); err != nil {
		return errors.New("cert_serial must be non-empty, even-length lowercase hexadecimal")
	}
	return nil
}

func validateVerificationCertSerial(certSerial string) error {
	if certSerial == "" || len(certSerial)%2 != 0 {
		return errors.New("cert_serial must be non-empty, even-length hexadecimal")
	}
	if _, err := hex.DecodeString(certSerial); err != nil {
		return errors.New("cert_serial must be non-empty, even-length hexadecimal")
	}
	return nil
}
