// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package tdx provides TDX quote generation and verification functionality without CGO dependency
package tdx

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"strings"
	"time"
)

// QuoteVerifier provides TDX quote verification functionality
type QuoteVerifier struct {
	collateralProvider CollateralProviderInterface
}

// VerificationResult contains the result of quote verification
// Based on Intel DCAP QVL: Status enum from QuoteVerification.h
type VerificationResult struct {
	ParsedQuote         *TdxEcdsaQuote    // Parsed quote structure
	CollateralExpStatus int               // collateral_expiration_status (0 OK, 1 expired)
	SupplementalData    *SupplementalData // complete supplemental data implementation (DCAP QVL: p_supplemental_data)
	SupplementalDataBuf []byte            // QVL-aligned supplemental data byte buffer (fixed layout per version)
	QvResult            QvResultType
}

// NewQuoteVerifier creates a new quote verifier
func NewQuoteVerifier(dcapServerURL string) *QuoteVerifier {
	return &QuoteVerifier{
		collateralProvider: NewCollateralProvider(dcapServerURL),
	}
}

// VerifyQuote verifies a TDX quote and returns the verification result
// Based on Intel DCAP QVL: QuoteVerification/QvE/Enclave/qve.cpp:1657-2107 (sgx_qve_verify_quote) -  Non-SERVTD_ATTEST mode
func (qv *QuoteVerifier) VerifyQuote(quote []byte) (*VerificationResult, QuoteErrType) {

	// Initialize result with default values as per DCAP QVL: qve.cpp:1676-1709
	result := &VerificationResult{
		CollateralExpStatus: 1,
		QvResult:            SGX_QL_QV_RESULT_UNSPECIFIED,
	}

	parsedQuote, err := ParseQuote(quote)
	if err != nil {
		// Return invalid parameter for parsing failure as per DCAP QVL: qve.cpp:1723
		return result, SGX_QL_ERROR_INVALID_PARAMETER
	}

	// Get collateral for verification
	collateral, err := qv.collateralProvider.GetCollateral(parsedQuote)
	if err != nil {
		return result, SGX_QL_UNABLE_TO_GET_COLLATERAL
	}

	// In SERVTD_ATTEST mode: could use QGS commend to get collateral from SERVTD. corresponds to DCAP QVL: qve.cpp:1717-1730 (SERVTD_ATTEST)
	// if (p_quote_collateral == NULL) {
	//   get_fmspc_ca_from_quote() -> tdx_att_get_collateral()
	// }

	// Setup expiration check date
	expirationCheckDate := time.Now().Unix()
	// Validate input parameters as per DCAP QVL: qve.cpp:1736-1750
	if quote == nil || len(quote) < QUOTE_MIN_SIZE || collateral == nil || expirationCheckDate <= 0 {
		// Return invalid parameter error as per DCAP QVL: qve.cpp:1749
		return result, SGX_QL_ERROR_INVALID_PARAMETER
	}

	// Validate collateral version as per DCAP QVL: qve.cpp:1752-1766
	if collateral.Version != QVE_COLLATERAL_VERSION1 &&
		collateral.Version != QVE_COLLATERAL_VERSION3 &&
		collateral.Version != QVE_COLLATERAL_VERSION31 &&
		collateral.Version != QVE_COLLATERAL_VERSION4 {
		// Return collateral version not supported error as per DCAP QVL: qve.cpp:1765
		return result, SGX_QL_COLLATERAL_VERSION_NOT_SUPPORTED
	}

	// Store the parsed quote in the result
	result.ParsedQuote = parsedQuote

	// Main verification operation in DCAP QVL: qve.cpp:1791-2051
	// default init value for ret and collateralVerificationRes
	var ret QuoteErrType = SGX_QL_ERROR_INVALID_PARAMETER
	var collateralVerificationRes Status = STATUS_SGX_ENCLAVE_REPORT_MRSIGNER_MISMATCH
	var tcbInfo *TcbInfo
	var qeIdentity *QeIdentity

	// Extract PCK certificate chain from quote as per DCAP QVL: qve.cpp:1805-1808
	certChain, extractRet := extractChainFromQuote(parsedQuote)
	if extractRet != SGX_QL_SUCCESS || certChain == nil {
		return result, extractRet
	}

	// Note: DCAP QVL qve.cpp:1812-1822 parses TCB Info into tcb_info_obj
	// Here we parse tcbinfo and qeidentity in advance to avoid repetitive parsing

	// First unmarshal: extract signature and raw json TcbInfo
	var tcbInfoWithSignature TcbInfoWithSignature
	if err := json.Unmarshal(collateral.TcbInfo, &tcbInfoWithSignature); err != nil {
		return result, SGX_QL_TCBINFO_UNSUPPORTED_FORMAT
	}
	// Second unmarshal: parse raw json TcbInfo into structure
	var tcbInfoStruct TcbInfo
	if err := json.Unmarshal(tcbInfoWithSignature.TcbInfo, &tcbInfoStruct); err != nil {
		return result, SGX_QL_TCBINFO_UNSUPPORTED_FORMAT
	}
	tcbInfo = &tcbInfoStruct

	// First unmarshal: extract signature and raw json QeIdentity
	var qeIdentityWithSignature QeIdentityWithSignature
	if err := json.Unmarshal(collateral.QeIdentity, &qeIdentityWithSignature); err != nil {
		return result, SGX_QL_QEIDENTITY_UNSUPPORTED_FORMAT
	}
	// Second unmarshal: parse raw json QeIdentity into structure
	var qeIdentityStruct QeIdentity
	if err := json.Unmarshal(qeIdentityWithSignature.EnclaveIdentity, &qeIdentityStruct); err != nil {
		return result, SGX_QL_QEIDENTITY_UNSUPPORTED_FORMAT
	}
	qeIdentity = &qeIdentityStruct

	// Parse PCK Cert chain and validate length: qve.cpp:1824-1830
	if err := qv.validateCertChainLength(certChain); err != nil {
		return result, SGX_QL_PCK_CERT_CHAIN_ERROR
	}

	// Check PEM CRL and create CRLs combined array as per DCAP QVL: qve.cpp:1832-1868
	// In DCAP QVL: check_pem_crl() -> check_hex_crl() -> byte_to_hexstring() -> create crls array
	crls, err := qv.parseAndCombineCrls(collateral)
	if err != nil {
		return result, SGX_QL_CRL_UNSUPPORTED_FORMAT
	}

	// Extract root CA from PCK cert chain as per DCAP QVL: qve.cpp:1871+
	if certChain.RootCA == nil {
		return result, SGX_QL_PCK_CERT_CHAIN_ERROR
	}

	// Check root certificate x509 format and extract public key as per DCAP QVL: qve.cpp:1882-1902
	// Since EcdsaCertChain.RootCA is already *x509.Certificate, we do not need to check here

	// Extract public key from root certificate as per DCAP QVL: qve.cpp:1890
	rootPubKeyFromCert := certChain.RootCA.PublicKey
	if rootPubKeyFromCert == nil {
		return result, SGX_QL_PCK_CERT_CHAIN_ERROR
	}

	// In non-SERVTD_ATTEST mode: use hardcoded Intel root public key as per DCAP QVL: qve.cpp:1894-1902
	// Compare with hardcoded Intel root public key
	switch key := rootPubKeyFromCert.(type) {
	case *ecdsa.PublicKey:
		// Serialize ECDSA public key in uncompressed format (starts with 0x04)
		// This matches the format of hardcoded INTEL_ROOT_PUB_KEY
		pubKeyBytes := append([]byte{0x04}, append(key.X.Bytes(), key.Y.Bytes()...)...)
		if !bytes.Equal(pubKeyBytes, INTEL_ROOT_PUB_KEY) {
			return result, SGX_QL_PCK_CERT_CHAIN_ERROR
		}
	default:
		// For non-ECDSA key types, return error
		return result, SGX_QL_PCK_CERT_CHAIN_ERROR
	}

	// Get collateral dates as per DCAP QVL: qve.cpp:1912-1932 (qve_get_collateral_dates)
	// This function extracts issue and expiration dates from all collateral components
	collateralDates, ret := qv.getCollateralDates(certChain, tcbInfo, qeIdentity, collateral, crls)
	if ret != SGX_QL_SUCCESS {
		return result, ret
	}

	// latestIssueDate := collateralDates.LatestIssueDate
	earliestExpirationDate := collateralDates.EarliestExpirationDate
	// Update expiration check date as per DCAP QVL: qve.cpp:1924-1928 (SERVTD_ATTEST mode)
	// In SERVTD_ATTEST mode: expiration_check_date = (latest_issue_date + earliest_expiration_date) / 2
	// In non-SERVTD_ATTEST mode: expirationCheckDate remains as getCurrentTime()
	if earliestExpirationDate <= expirationCheckDate {
		result.CollateralExpStatus = 1
	} else {
		result.CollateralExpStatus = 0
	}

	// Parse and verify PCK certificate chain as per DCAP QVL: qve.cpp:1940-1949
	collateralVerificationRes = qv.sgxAttestationVerifyPCKCertificate(certChain, crls, certChain.RootCA, expirationCheckDate)
	if collateralVerificationRes != STATUS_OK {
		fmt.Printf("DEBUG: PCK certificate verification failed with status: %v (0x%04X)\n", collateralVerificationRes, int(collateralVerificationRes))
		if isExpirationError(collateralVerificationRes) {
			result.CollateralExpStatus = 1
		} else {
			ret = statusToQuoteErr(collateralVerificationRes)
			return result, ret
		}
	}

	tcbSigningChain, err := ParseCertChain(collateral.TcbInfoIssuerChain)
	if err != nil {
		fmt.Printf("DEBUG: TCB Info signing chain parsing failed: %v\n", err)
		return result, SGX_QL_PCK_CERT_CHAIN_ERROR
	}
	// fmt.Printf("DEBUG: TCB Info signing chain parsed successfully, RootCA: %v, IntermediateCA: %v, TopMostCert: %v\n",
	// 	tcbSigningChain.RootCA != nil, getIntermediateCert(tcbSigningChain) != nil, tcbSigningChain.TopMostCert != nil)
	if tcbSigningChain.TopMostCert != nil {
		// fmt.Printf("DEBUG: TCB TopMostCert CN: %s\n", tcbSigningChain.TopMostCert.Subject.CommonName)
	}
	// Parse and verify TCB info as per DCAP QVL: qve.cpp:1952-1962
	collateralVerificationRes = qv.sgxAttestationVerifyTCBInfo(&tcbInfoWithSignature, tcbInfo, tcbSigningChain, crls[0], certChain.RootCA, expirationCheckDate)
	if collateralVerificationRes != STATUS_OK {
		if isExpirationError(collateralVerificationRes) {
			result.CollateralExpStatus = 1
		} else {
			ret = statusToQuoteErr(collateralVerificationRes)
			return result, ret
		}
	}

	qeIdentitySigningChain, err := ParseCertChain(collateral.QeIdentityIssuerChain)
	if err != nil {
		return result, SGX_QL_PCK_CERT_CHAIN_ERROR
	}
	// Parse and verify QE identity as per DCAP QVL: qve.cpp:1965-1975
	collateralVerificationRes = qv.sgxAttestationVerifyEnclaveIdentity(&qeIdentityWithSignature, qeIdentity, qeIdentitySigningChain, crls[0], certChain.RootCA, expirationCheckDate)
	if collateralVerificationRes != STATUS_OK {
		if isExpirationError(collateralVerificationRes) {
			result.CollateralExpStatus = 1
		} else {
			ret = statusToQuoteErr(collateralVerificationRes)
			return result, ret
		}
	}

	// Parse and verify the quote, update verification results as per DCAP QVL: qve.cpp:1979-1987
	collateralVerificationRes = qv.sgxAttestationVerifyQuote(quote, crls[1], certChain.PCKCert, tcbInfo, qeIdentity)
	result.QvResult = statusToQvResult(collateralVerificationRes)

	if isNonTerminalError(collateralVerificationRes) {
		ret = SGX_QL_SUCCESS
	} else {
		ret = statusToQuoteErr(collateralVerificationRes)
	}

	// Collect supplemental data if required as per DCAP QVL: qve.cpp:1991-2020
	if ret == SGX_QL_SUCCESS {
		supplementalData, err := qv.setQuoteSupplementalData(tcbInfo, qeIdentity, certChain, parsedQuote, collateralDates, crls)
		if err != nil {
			// Log warning but don't fail verification for supplemental data issues
			// This matches Intel QVL behavior where supplemental data is optional
			_ = err // TODO: Add proper logging
		} else {
			result.SupplementalData = supplementalData
			// Build QVL-aligned byte buffer for supplemental data (fixed version layout)
			if buf, err := qv.packSupplementalData(supplementalData); err == nil {
				result.SupplementalDataBuf = buf
			}
		}
	}

	// If any check or operation failed, set verification result to unspecified as per DCAP QVL: qve.cpp:2102-2104
	if ret != SGX_QL_SUCCESS {
		result.QvResult = SGX_QL_QV_RESULT_UNSPECIFIED
	}

	return result, ret
}

// sgxAttestationVerifyPCKCertificate verifies the PCK certificate chain according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:90-146 (sgxAttestationVerifyPCKCertificate)
func (qv *QuoteVerifier) sgxAttestationVerifyPCKCertificate(certChain *EcdsaCertChain, crls []*x509.RevocationList, rootCert *x509.Certificate, expirationCheckDate int64) Status {

	// Perform heavy PCK chain verification (structure, signatures, validity)
	// Parameter validation as per DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:103-111
	if certChain == nil || rootCert == nil {
		return STATUS_INVALID_PARAMETER
	}

	if crls == nil || len(crls) < 2 || crls[0] == nil || crls[1] == nil {
		return STATUS_UNSUPPORTED_CERT_FORMAT
	}

	// Certificate chain validation as per DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:113-127
	if err := qv.validateCertChainLength(certChain); err != nil {
		return STATUS_UNSUPPORTED_CERT_FORMAT
	}

	// CRL format check in DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:129-140
	// have been checked before

	// Verify PCK Cert chain as per DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:145 (PckCertVerifier::verify)
	if status := qv.verifyPCKCertificateChain(certChain, crls, rootCert, expirationCheckDate); status != STATUS_OK {
		return status
	}

	return STATUS_OK
}

// verifyPCKCertificateChain verifies the complete PCK certificate chain according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/PckCertVerifier.cpp:53-202 (PckCertVerifier::verify)
func (qv *QuoteVerifier) verifyPCKCertificateChain(chain *EcdsaCertChain, crls []*x509.RevocationList, rootCert *x509.Certificate, expirationCheckDate int64) Status {
	// Step 1: Certificate chain structure verification as per DCAP QVL: PckCertVerifier.cpp:59-96
	// Check Root CA is present as per DCAP QVL: PckCertVerifier.cpp:59-64
	if chain.RootCA == nil {
		return STATUS_SGX_ROOT_CA_MISSING
	}

	// Verify Root CA CN contains required phrase as per DCAP QVL: PckCertVerifier.cpp:66-70
	if !strings.Contains(chain.RootCA.Subject.CommonName, SGX_ROOT_CA_CN_PHRASE) {
		return STATUS_SGX_ROOT_CA_MISSING
	}

	// Check Intermediate CA is present as per DCAP QVL: PckCertVerifier.cpp:72-77
	intermediateCA := getIntermediateCert(chain)
	if intermediateCA == nil {
		return STATUS_SGX_INTERMEDIATE_CA_MISSING
	}

	// Verify Intermediate CA CN contains required phrase as per DCAP QVL: PckCertVerifier.cpp:79-83
	if !strings.Contains(intermediateCA.Subject.CommonName, SGX_INTERMEDIATE_CN_PHRASE) {
		return STATUS_SGX_INTERMEDIATE_CA_MISSING
	}

	// Check PCK Certificate is present and verify CN as per DCAP QVL: PckCertVerifier.cpp:85-96
	if status := qv.verifyPckCertificateCN(chain.PCKCert); status != STATUS_OK {
		return STATUS_SGX_PCK_MISSING
	}

	// Step 2: Certificate signature verification as per DCAP QVL: PckCertVerifier.cpp:98-117
	if status := qv.verifyCertificateSignatures(chain); status != STATUS_OK {
		return status
	}

	// Step 3: Trusted root CA verification as per DCAP QVL: PckCertVerifier.cpp:119-129
	// Verify that the trusted root CA is self-signed as per DCAP QVL: PckCertVerifier.cpp:119-123
	if rootCert.Subject.String() != rootCert.Issuer.String() {
		return STATUS_TRUSTED_ROOT_CA_INVALID
	}

	// Verify that the signature of trusted root matches the signature of root cert from PCK chain
	// Based on DCAP QVL: PckCertVerifier.cpp:125-129
	if !bytes.Equal(rootCert.Signature, chain.RootCA.Signature) {
		return STATUS_SGX_PCK_CERT_CHAIN_UNTRUSTED
	}

	// Step 4: CRL verification as per DCAP QVL: PckCertVerifier.cpp:134-158
	rootCaCrl := crls[0]
	intermediateCrl := crls[1]

	// Verify Root CA CRL as per DCAP QVL: PckCertVerifier.cpp:134-139
	if rootCaCrl.Issuer.String() != chain.RootCA.Subject.String() {
		return STATUS_SGX_CRL_UNKNOWN_ISSUER
	}
	if err := rootCaCrl.CheckSignatureFrom(chain.RootCA); err != nil {
		return STATUS_SGX_CRL_INVALID_SIGNATURE
	}

	// Verify Intermediate CA CRL as per DCAP QVL: PckCertVerifier.cpp:141-146
	if intermediateCrl.Issuer.String() != intermediateCA.Subject.String() {
		return STATUS_SGX_CRL_UNKNOWN_ISSUER
	}
	if err := intermediateCrl.CheckSignatureFrom(intermediateCA); err != nil {
		return STATUS_SGX_CRL_INVALID_SIGNATURE
	}

	// Check if Intermediate CA is revoked by Root CA CRL as per DCAP QVL: PckCertVerifier.cpp:148-152
	for _, revokedCert := range rootCaCrl.RevokedCertificateEntries {
		if revokedCert.SerialNumber.Cmp(intermediateCA.SerialNumber) == 0 {
			return STATUS_SGX_INTERMEDIATE_CA_REVOKED
		}
	}

	// Check if PCK Certificate is revoked by Intermediate CA CRL as per DCAP QVL: PckCertVerifier.cpp:154-158
	for _, revokedCert := range intermediateCrl.RevokedCertificateEntries {
		if revokedCert.SerialNumber.Cmp(chain.PCKCert.SerialNumber) == 0 {
			fmt.Printf("DEBUG: PCK Certificate revoked by Intermediate CA CRL in verifyPCKCertificateChain\n")
			return STATUS_SGX_PCK_REVOKED
		}
	}

	// Step 5: Certificate expiration verification as per DCAP QVL: PckCertVerifier.cpp:160-182
	checkTime := time.Unix(expirationCheckDate, 0)

	// Check Root CA expiration as per DCAP QVL: PckCertVerifier.cpp:160-166
	if checkTime.After(chain.RootCA.NotAfter) {
		return STATUS_SGX_PCK_CERT_CHAIN_EXPIRED
	}

	// Check Intermediate CA expiration as per DCAP QVL: PckCertVerifier.cpp:168-174
	if checkTime.After(intermediateCA.NotAfter) {
		return STATUS_SGX_PCK_CERT_CHAIN_EXPIRED
	}

	// Check PCK Certificate expiration as per DCAP QVL: PckCertVerifier.cpp:176-182
	if checkTime.After(chain.PCKCert.NotAfter) {
		return STATUS_SGX_PCK_CERT_CHAIN_EXPIRED
	}

	// Step 6: CRL expiration verification as per DCAP QVL: PckCertVerifier.cpp:184-200
	// Check Root CA CRL expiration as per DCAP QVL: PckCertVerifier.cpp:184-191
	if checkTime.After(rootCaCrl.NextUpdate) {
		return STATUS_SGX_CRL_EXPIRED
	}

	// Check Intermediate CA CRL expiration as per DCAP QVL: PckCertVerifier.cpp:193-200
	if checkTime.After(intermediateCrl.NextUpdate) {
		return STATUS_SGX_CRL_EXPIRED
	}

	return STATUS_OK
}

// sgxAttestationVerifyTCBInfo verifies TCB Info according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:190-268 (sgxAttestationVerifyTCBInfo)
func (qv *QuoteVerifier) sgxAttestationVerifyTCBInfo(tcbInfoWithSignature *TcbInfoWithSignature, tcbInfo *TcbInfo, tcbInfoIssuerChain *EcdsaCertChain, rootCaCrl *x509.RevocationList, rootCert *x509.Certificate, expirationCheckDate int64) Status {
	// Parameter validation as per DCAP QVL: QuoteVerification.cpp:205-212
	if tcbInfoWithSignature.Signature == "" || tcbInfo == nil || tcbInfoIssuerChain == nil || rootCaCrl == nil || rootCert == nil {
		return STATUS_UNSUPPORTED_CERT_FORMAT
	}

	// Parse TCB Info from raw JSON as per DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:215-229
	// Have been parsed before

	// Parse TCB signing certificate chain as per DCAP QVL: QuoteVerification.cpp:231-237
	// Have done before

	// Verify TCB signing certificate chain length as per DCAP QVL: QuoteVerification.cpp:239-244
	if len(tcbInfoIssuerChain.Certificates) != EXPECTED_CERTIFICATE_COUNT_IN_TCB_CHAIN {
		return STATUS_UNSUPPORTED_CERT_FORMAT
	}

	// ROOT CA CRL format check in DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:246-251
	// have been checked before

	// Verify TCB Info as per DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:256 (TCBInfoVerifier::verify)
	// Step 1: Verify TCB signing certificate chain as per DCAP QVL: TCBInfoVerifier.cpp:61-65
	// _tcbSigningChain->verify(chain, rootCaCrl, trustedRoot);
	if status := qv.verifyTCBSigningChain(tcbInfoIssuerChain, rootCaCrl, rootCert); status != STATUS_OK {
		fmt.Printf("DEBUG: TCB signing chain verification failed with status: %v (0x%04X)\n", status, int(status))
		return status
	}

	// Step 2: Verify TCB Info signature as per DCAP QVL: TCBInfoVerifier.cpp:67-73
	// _commonVerifier->checkSha256EcdsaSignature(tcbJson.getSignature(), tcbJson.getInfoBody(), tcbSigningCert->getPubKey())
	if status := qv.verifyCollateralSignature(tcbInfoWithSignature.Signature, tcbInfoWithSignature.TcbInfo, tcbInfoIssuerChain); status != STATUS_OK {
		return status
	}

	// Step 3: Check certificate expiration as per DCAP QVL: TCBInfoVerifier.cpp:75-86
	checkTime := time.Unix(expirationCheckDate, 0)
	rootCa := tcbInfoIssuerChain.RootCA
	// Check Root CA expiration as per DCAP QVL: TCBInfoVerifier.cpp:76-80
	if checkTime.After(rootCa.NotAfter) {
		return STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED
	}
	// Check TCB Signing Certificate expiration as per DCAP QVL: TCBInfoVerifier.cpp:82-86
	// Get topmost certificate (TCB Signing Certificate) as per DCAP QVL: TCBInfoVerifier.cpp:67 (chain.getTopmostCert())
	tcbSigningCert := tcbInfoIssuerChain.TopMostCert
	if checkTime.After(tcbSigningCert.NotAfter) {
		return STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED
	}

	// Check CRL expiration as per DCAP QVL: TCBInfoVerifier.cpp:88-92
	if checkTime.After(rootCaCrl.NextUpdate) {
		return STATUS_SGX_CRL_EXPIRED
	}

	// Check TCB Info expiration as per DCAP QVL: TCBInfoVerifier.cpp:94-98
	// if(expirationDate > tcbJson.getNextUpdate())
	if tcbInfo.NextUpdate == "" {
		return STATUS_SGX_TCB_INFO_EXPIRED
	}
	nextUpdate, err := time.Parse(time.RFC3339, tcbInfo.NextUpdate)
	if err != nil {
		return STATUS_SGX_TCB_INFO_EXPIRED
	}
	if checkTime.After(nextUpdate) {
		return STATUS_SGX_TCB_INFO_EXPIRED
	}

	return STATUS_OK
}

// verifyTCBSigningChain verifies TCB signing certificate chain according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/TCBSigningChain.cpp:52-123 (TCBSigningChain::verify)
func (qv *QuoteVerifier) verifyTCBSigningChain(chain *EcdsaCertChain, rootCaCrl *x509.RevocationList, trustedRoot *x509.Certificate) Status {
	// Verify Root CA as per DCAP QVL: TCBSigningChain.cpp:57-62
	rootCert := chain.RootCA
	if rootCert == nil {
		fmt.Printf("DEBUG: Root CA is nil in verifyTCBSigningChain\n")
		return STATUS_SGX_ROOT_CA_MISSING
	}

	// Check Root CA CN contains required phrase as per DCAP QVL: TCBSigningChain.cpp:63-68
	if !strings.Contains(rootCert.Subject.CommonName, SGX_ROOT_CA_CN_PHRASE) {
		fmt.Printf("DEBUG: Root CA CN does not contain required phrase: %s\n", rootCert.Subject.CommonName)
		return STATUS_SGX_ROOT_CA_MISSING
	}

	// Verify Root CA certificate as per DCAP QVL: TCBSigningChain.cpp:70-75
	if rootCert.Subject.String() != rootCert.Issuer.String() {
		return STATUS_SGX_ROOT_CA_INVALID_ISSUER
	}
	if err := rootCert.CheckSignatureFrom(rootCert); err != nil {
		return STATUS_SGX_ROOT_CA_INVALID_ISSUER
	}

	// Check Topmost Cert as per DCAP QVL: TCBSigningChain.cpp:77-88
	tcbSigningCert := chain.TopMostCert
	if tcbSigningCert == nil {
		return STATUS_SGX_TCB_SIGNING_CERT_MISSING
	}
	if !strings.Contains(tcbSigningCert.Subject.CommonName, SGX_TCB_SIGNING_CN_PHRASE) {
		fmt.Printf("DEBUG: TCB Signing Cert CN: %s\n", tcbSigningCert.Subject.CommonName)
		return STATUS_SGX_TCB_SIGNING_CERT_MISSING
	}

	// Verify TCB Signing Certificate as per DCAP QVL: TCBSigningChain.cpp:90-95
	if tcbSigningCert.Issuer.String() != rootCert.Subject.String() {
		return STATUS_SGX_TCB_SIGNING_CERT_INVALID_ISSUER
	}
	if err := tcbSigningCert.CheckSignatureFrom(rootCert); err != nil {
		return STATUS_SGX_TCB_SIGNING_CERT_INVALID_ISSUER
	}

	// Verify CRL as per DCAP QVL: TCBSigningChain.cpp:97-102
	if rootCaCrl.Issuer.String() != rootCert.Subject.String() {
		return STATUS_SGX_CRL_UNKNOWN_ISSUER
	}
	if err := rootCaCrl.CheckSignatureFrom(rootCert); err != nil {
		return STATUS_SGX_CRL_INVALID_SIGNATURE
	}

	// Check if TCB Signing Certificate is revoked as per DCAP QVL: TCBSigningChain.cpp:104-108
	for _, revokedCert := range rootCaCrl.RevokedCertificateEntries {
		if revokedCert.SerialNumber.Cmp(tcbSigningCert.SerialNumber) == 0 {
			fmt.Printf("DEBUG: TCB Signing Certificate revoked in verifyTCBSigningChain\n")
			return STATUS_SGX_TCB_SIGNING_CERT_REVOKED
		}
	}

	// Verify trusted root CA as per DCAP QVL: TCBSigningChain.cpp:110-120
	if trustedRoot.Subject.String() != trustedRoot.Issuer.String() {
		return STATUS_TRUSTED_ROOT_CA_INVALID
	}
	if !bytes.Equal(trustedRoot.Signature, rootCert.Signature) {
		return STATUS_SGX_TCB_SIGNING_CERT_CHAIN_UNTRUSTED
	}

	return STATUS_OK
}

// verifyCollateralSignature verifies collateral signature according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: TCBInfoVerifier.cpp:67-73 and EnclaveIdentityVerifier.cpp:67-73 (checkSha256EcdsaSignature)
func (qv *QuoteVerifier) verifyCollateralSignature(signature string, infoBody json.RawMessage, certChain *EcdsaCertChain) Status {
	// Step 1: Extract signature (hex string to bytes)
	signatureBytes, err := hex.DecodeString(signature)
	if err != nil {
		return STATUS_TCB_INFO_INVALID_SIGNATURE
	}

	// Step 2: Get TCB signing certificate (topmost cert) as per DCAP QVL: TCBInfoVerifier.cpp:67
	tcbSigningCert := certChain.TopMostCert
	if tcbSigningCert == nil {
		fmt.Printf("DEBUG: TCB signing certificate is nil in verifyCollateralSignature\n")
		return STATUS_TCB_INFO_INVALID_SIGNATURE
	}

	// Step 3: Get public key from TCB signing certificate
	tcbPublicKey, ok := tcbSigningCert.PublicKey.(*ecdsa.PublicKey)
	if !ok {
		return STATUS_TCB_INFO_INVALID_SIGNATURE
	}

	// Step 4: Verify ECDSA signature using existing VerifyECDSASignature function
	// Based on Intel DCAP QVL: CommonVerifier::checkSha256EcdsaSignature
	if err := VerifyECDSASignature(tcbPublicKey, infoBody, signatureBytes); err != nil {
		return STATUS_TCB_INFO_INVALID_SIGNATURE
	}

	return STATUS_OK
}

// sgxAttestationVerifyEnclaveIdentity verifies QE identity according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:270-341 (sgxAttestationVerifyEnclaveIdentity)
func (qv *QuoteVerifier) sgxAttestationVerifyEnclaveIdentity(qeIdentityWithSignature *QeIdentityWithSignature, qeIdentity *QeIdentity, qeIdentitySigningChain *EcdsaCertChain, rootCaCrl *x509.RevocationList, rootCert *x509.Certificate, expirationCheckDate int64) Status {
	// Parameter validation as per DCAP QVL: QuoteVerification.cpp:284-291
	if qeIdentityWithSignature.Signature == "" || qeIdentity == nil || qeIdentitySigningChain == nil || rootCaCrl == nil || rootCert == nil {
		return STATUS_UNSUPPORTED_CERT_FORMAT
	}

	// Parse QE Identity from raw JSON as per DCAP QVL: QuoteVerification.cpp:293-302
	// Have parsed before

	// Parse QE Identity signing certificate chain as per DCAP QVL: QuoteVerification.cpp:304-310
	// Have done before

	// Verify QE Identity signing certificate chain length as per DCAP QVL: QuoteVerification.cpp:312-317
	if len(qeIdentitySigningChain.Certificates) != EXPECTED_CERTIFICATE_COUNT_IN_TCB_CHAIN {
		return STATUS_UNSUPPORTED_CERT_FORMAT
	}

	// ROOT CA CRL format check in DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:319-324
	// have been checked before

	// Verify QE Identity as per DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:329 (EnclaveIdentityVerifier::verify)
	// Step 1: Verify TCB signing certificate chain as per DCAP QVL: EnclaveIdentityVerifier.cpp:61-65
	// _tcbSigningChain->verify(chain, rootCaCrl, trustedRoot);
	if status := qv.verifyTCBSigningChain(qeIdentitySigningChain, rootCaCrl, rootCert); status != STATUS_OK {
		return status
	}

	// Step 2: Verify QE Identity signature as per DCAP QVL: EnclaveIdentityVerifier.cpp:67-73
	// _commonVerifier->checkSha256EcdsaSignature(enclaveIdentity.getSignature(), enclaveIdentity.getBody(), tcbSigningCert->getPubKey())
	if status := qv.verifyCollateralSignature(qeIdentityWithSignature.Signature, qeIdentityWithSignature.EnclaveIdentity, qeIdentitySigningChain); status != STATUS_OK {
		return status
	}

	// Step 3: Check certificate expiration as per DCAP QVL: EnclaveIdentityVerifier.cpp:75-101
	checkTime := time.Unix(expirationCheckDate, 0)
	rootCa := qeIdentitySigningChain.RootCA
	if checkTime.After(rootCa.NotAfter) {
		return STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED
	}

	// Get topmost certificate (TCB Signing Certificate) as per DCAP QVL: EnclaveIdentityVerifier.cpp:67 (chain.getTopmostCert())
	tcbSigningCert := qeIdentitySigningChain.TopMostCert
	if checkTime.After(tcbSigningCert.NotAfter) {
		return STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED
	}

	if checkTime.After(rootCaCrl.NextUpdate) {
		return STATUS_SGX_CRL_EXPIRED
	}

	// Check QE Identity expiration as per DCAP QVL: EnclaveIdentityVerifier.cpp:103-110
	// if(expirationDate > enclaveIdentity.getNextUpdate())
	if qeIdentity.NextUpdate == "" {
		return STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED
	}
	nextUpdate, err := time.Parse(time.RFC3339, qeIdentity.NextUpdate)
	if err != nil {
		return STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED
	}
	if checkTime.After(nextUpdate) {
		return STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED
	}

	return STATUS_OK
}

// sgxAttestationVerifyQuote implements the QuoteVerifier workflow (4.1.2.4.x)
// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:343-416 (sgxAttestationVerifyQuote)
func (qv *QuoteVerifier) sgxAttestationVerifyQuote(quote []byte, pckCrl *x509.RevocationList, pckCert *x509.Certificate, tcbInfo *TcbInfo, qeIdentity *QeIdentity) Status {

	// 4.1.2.4.1 Parameter validation
	// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:347-354
	if quote == nil || pckCrl == nil || pckCert == nil || tcbInfo == nil {
		return STATUS_MISSING_PARAMETERS
	}

	// Verify quote format (4.1.2.4.2)
	// Parse the quote
	parsedQuote, err := ParseQuote(quote)
	if err != nil {
		return STATUS_UNSUPPORTED_QUOTE_FORMAT
	}
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Quote.cpp:200-249
	if !qv.validate(parsedQuote) {
		return STATUS_UNSUPPORTED_QUOTE_FORMAT
	}

	// Parse and verify PCK certificate format (4.1.2.4.3)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Quote.cpp:412-415
	// have done before

	// Verify PCK certificate CN short phrase (4.1.2.4.4)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:64-68
	if status := qv.verifyPckCertificateCN(pckCert); status != STATUS_OK {
		return status
	}

	// Verify PCK CRL format (4.1.2.4.5)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:64-68
	// pckCrl, status := qv.parsePckCrl(collateral)
	// if status != STATUS_OK {
	// 	return status
	// }
	// have been verified in outer function

	// Verify CRL issuer(4.1.2.4.6)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:71-75
	if status := qv.verifyPckCrlIssuer(pckCrl, pckCert); status != STATUS_OK {
		return status
	}

	// Check if PCK certificate is revoked (4.1.2.4.7)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:87-91
	if status := qv.checkPckCertificateRevocation(pckCrl, pckCert); status != STATUS_OK {
		return status
	}

	// Parse TCB Info JSON and perform basic validation (4.1.2.4.8)
	// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification.cpp:376-391

	// TCB Info struct have been parsed in outer function
	// Validate TCB Info version, we only support v3 here
	// Based on Intel DCAP QVL: TcbInfo.cpp:189-196
	if tcbInfo.Version != 2 && tcbInfo.Version != 3 {
		return STATUS_UNSUPPORTED_TCB_INFO_FORMAT
	}
	// Validate TCB Info ID field
	// Based on Intel DCAP QVL: TcbInfo.cpp:213-218
	if tcbInfo.Version == 3 && tcbInfo.ID != "TDX" && tcbInfo.ID != "SGX" {
		return STATUS_UNSUPPORTED_TCB_INFO_FORMAT
	}

	// Parse QE Identity JSON and perform basic validation for later use
	// Based on Intel DCAP QVL: EnclaveIdentityParser.cpp:43-118 and EnclaveIdentityV2.cpp:46-75

	// QE Identity struct have been parsed on outer function
	// Validate parsed QE Identity structure
	if qeIdentity != nil {
		// Validate QE Identity version (only support version 2)
		// Based on Intel DCAP QVL: EnclaveIdentityParser.cpp:98-117
		if qeIdentity.Version != 2 {
			return STATUS_UNSUPPORTED_QE_IDENTITY_FORMAT
		}
		// Validate QE Identity v2 ID field
		// Based on Intel DCAP QVL: EnclaveIdentityV2.cpp:231-253
		if qeIdentity.ID != "QE" && qeIdentity.ID != "QVE" && qeIdentity.ID != "TD_QE" {
			return STATUS_UNSUPPORTED_QE_IDENTITY_FORMAT
		}
		// Validate hex field lengths
		if len(qeIdentity.MiscSelect) != 8 || len(qeIdentity.MiscSelectMask) != 8 ||
			len(qeIdentity.Attributes) != 32 || len(qeIdentity.AttributesMask) != 32 ||
			len(qeIdentity.MrSigner) != 64 || len(qeIdentity.TcbLevels) == 0 {
			return STATUS_UNSUPPORTED_QE_IDENTITY_FORMAT
		}
	}

	// TEE type match validation (4.1.2.4.9)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:94-114
	if tcbInfo.Version >= 3 {
		// For TCB Info version 3 and above, check ID field (not TCBType)
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:96-105
		if tcbInfo.ID == "TDX" {
			if parsedQuote.Header.TeeType != TEE_TYPE_TDX {
				return STATUS_TCB_INFO_MISMATCH
			}
		} else if tcbInfo.ID == "SGX" {
			if parsedQuote.Header.TeeType != TEE_TYPE_SGX {
				return STATUS_TCB_INFO_MISMATCH
			}
		} else {
			// Unknown TCB Info ID
			return STATUS_TCB_INFO_MISMATCH
		}
	} else {
		// For deprecated TCB Info versions (< 3), TDX is not supported
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:107-114
		if parsedQuote.Header.TeeType == TEE_TYPE_TDX {
			return STATUS_TCB_INFO_MISMATCH
		}
	}

	// FMSPC and PCEID match validation (4.1.2.4.10)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:116-129
	fmspcFromCert, pceIdFromCert, err := ExtractSgxExtensions(pckCert)
	if err != nil {
		return STATUS_INVALID_PCK_CERT
	}

	// Convert TCB Info hex strings to bytes for comparison
	fmspcFromTcb, err := hex.DecodeString(tcbInfo.Fmspc)
	if err != nil {
		return STATUS_UNSUPPORTED_TCB_INFO_FORMAT
	}
	pceIdFromTcb, err := hex.DecodeString(tcbInfo.PceId)
	if err != nil {
		return STATUS_UNSUPPORTED_TCB_INFO_FORMAT
	}

	// Compare FMSPC values
	if !bytes.Equal(fmspcFromTcb, fmspcFromCert) {
		return STATUS_TCB_INFO_MISMATCH
	}
	// Compare PCEID values
	if !bytes.Equal(pceIdFromTcb, pceIdFromCert) {
		return STATUS_TCB_INFO_MISMATCH
	}

	if pckCert.PublicKey == nil {
		return STATUS_INVALID_PCK_CERT
	}
	if _, ok := pckCert.PublicKey.(*ecdsa.PublicKey); !ok {
		return STATUS_INVALID_PCK_CERT
	}

	var tdxModuleIdentity *TdxModuleIdentity
	// TDX module validation (4.1.2.4.11) - TDX only
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:147-218
	if tcbInfo.Version >= 3 && tcbInfo.ID == "TDX" {
		// Extract TDX module data from quote
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:150-157
		tdxModule := tcbInfo.TdxModule
		var quoteMrSignerSeam [48]byte
		var quoteSeamAttributes [8]byte

		switch report := parsedQuote.Report.(type) {
		case TdReport10:
			copy(quoteMrSignerSeam[:], report.MrSignerSeam[:])
			copy(quoteSeamAttributes[:], report.SeamAttributes[:])
		case TdReport15:
			copy(quoteMrSignerSeam[:], report.MrSignerSeam[:])
			copy(quoteSeamAttributes[:], report.SeamAttributes[:])
		default:
			return STATUS_TDX_MODULE_MISMATCH
		}
		teeTcbSvn, err := qv.extractTeeTcbSvn(parsedQuote)
		if err != nil || len(teeTcbSvn) < 2 {
			return STATUS_TDX_MODULE_MISMATCH
		}
		tdxModuleVersion := teeTcbSvn[1]

		var tdxModuleMrSigner []byte
		var tdxModuleAttributes []byte
		var tdxModuleAttributesMask []byte

		// Convert from string to []byte
		tdxModuleMrSigner, err = hex.DecodeString(tdxModule.MrSigner)
		if err != nil {
			return STATUS_TDX_MODULE_MISMATCH
		}
		tdxModuleAttributes, err = hex.DecodeString(tdxModule.Attributes)
		if err != nil {
			return STATUS_TDX_MODULE_MISMATCH
		}
		tdxModuleAttributesMask, err = hex.DecodeString(tdxModule.AttributesMask)
		if err != nil {
			return STATUS_TDX_MODULE_MISMATCH
		}

		if parsedQuote.Header.Version > QUOTE_VERSION_3 && tdxModuleVersion > 0 {
			// Find TDX Module Identity based on version
			// Based on Intel DCAP QVL: QuoteVerifier.cpp:171
			tdxModuleIdentity = qv.findTdxModuleIdentity(tcbInfo.TdxModuleIdentities, tdxModuleVersion)
			if tdxModuleIdentity == nil {
				fmt.Printf("DEBUG: TDX Module Identity not found for version %d\n", tdxModuleVersion)
				return STATUS_TDX_MODULE_MISMATCH
			}

			mrSignerBytes, err := hex.DecodeString(tdxModuleIdentity.MrSigner)
			if err != nil {
				return STATUS_TDX_MODULE_MISMATCH
			}
			tdxModuleMrSigner = mrSignerBytes

			attributesBytes, err := hex.DecodeString(tdxModuleIdentity.Attributes)
			if err != nil {
				return STATUS_TDX_MODULE_MISMATCH
			}
			tdxModuleAttributes = attributesBytes

			maskBytes, err := hex.DecodeString(tdxModuleIdentity.AttributesMask)
			if err != nil {
				return STATUS_TDX_MODULE_MISMATCH
			}
			tdxModuleAttributesMask = maskBytes
		}
		_ = tdxModuleAttributesMask

		// Step 4.1.2.4.11.1: MRSIGNERSEAM validation
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:181-198
		if len(quoteMrSignerSeam) != len(tdxModuleMrSigner) {
			return STATUS_TDX_MODULE_MISMATCH
		}
		if !bytes.Equal(quoteMrSignerSeam[:], tdxModuleMrSigner) {
			return STATUS_TDX_MODULE_MISMATCH
		}

		// Step 4.1.2.4.11.2: SEAMATTRIBUTES validation
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:200-218
		if len(tdxModuleAttributes) != len(quoteSeamAttributes) {
			return STATUS_TDX_MODULE_MISMATCH
		}
		// Check attributes byte by byte
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:208-217
		for i := 0; i < len(quoteSeamAttributes); i++ {
			if quoteSeamAttributes[i] != 0 || quoteSeamAttributes[i] != tdxModuleAttributes[i] {
				return STATUS_TDX_MODULE_MISMATCH
			}
		}
	}

	// QE Report signature validation (4.1.2.4.12)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:221-227
	if status := qv.verifyQeReportSignature(pckCert, parsedQuote, quote); status != STATUS_OK {
		return status
	}

	// QE Report Data validation (4.1.2.4.13)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:229-248
	if status := qv.verifyQeReportData(parsedQuote); status != STATUS_OK {
		return status
	}

	qeIdentityStatus := STATUS_OK
	if qeIdentity != nil {
		// QE Identity validation (4.1.2.4.14)
		// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:252-281
		if status := qv.verifyQeIdentity(qeIdentity, parsedQuote); status != STATUS_OK {
			return status
		}

		// QE Identity Report verification (4.1.2.4.15)
		// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:284-302
		qeIdentityStatus = qv.verifyQeIdentityReport(qeIdentity, parsedQuote)
		switch qeIdentityStatus {
		case STATUS_SGX_ENCLAVE_REPORT_UNSUPPORTED_FORMAT:
			return STATUS_UNSUPPORTED_QUOTE_FORMAT
		case STATUS_SGX_ENCLAVE_IDENTITY_UNSUPPORTED_FORMAT,
			STATUS_SGX_ENCLAVE_IDENTITY_INVALID,
			STATUS_SGX_ENCLAVE_IDENTITY_UNSUPPORTED_VERSION:
			return STATUS_UNSUPPORTED_QE_IDENTITY_FORMAT
		case STATUS_SGX_ENCLAVE_REPORT_MISCSELECT_MISMATCH,
			STATUS_SGX_ENCLAVE_REPORT_ATTRIBUTES_MISMATCH,
			STATUS_SGX_ENCLAVE_REPORT_MRSIGNER_MISMATCH,
			STATUS_SGX_ENCLAVE_REPORT_ISVPRODID_MISMATCH:
			return STATUS_QE_IDENTITY_MISMATCH
		case STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE,
			STATUS_SGX_ENCLAVE_REPORT_ISVSVN_REVOKED:
			// Continue processing for these statuses
		default:
			// Continue processing for other statuses
		}
	}

	// Quote signature validation (4.1.2.4.16)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:311-320
	if status := qv.verifyQuoteSignature(parsedQuote, quote); status != STATUS_OK {
		return status
	}

	// TCB Level check (4.1.2.4.17)
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:324-326
	return qv.checkTcbLevel(tcbInfo, pckCert, parsedQuote, qeIdentityStatus, tdxModuleIdentity)

}

// validate verifies the quote format according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Quote.cpp:200-249
func (qv *QuoteVerifier) validate(quote *TdxEcdsaQuote) bool {
	// Based on Intel DCAP QVL: Quote.cpp:202 - Version validation
	if quote.Header.Version != QUOTE_VERSION_3 &&
		quote.Header.Version != QUOTE_VERSION_4 &&
		quote.Header.Version != QUOTE_VERSION_5 {
		return false
	}

	// Based on Intel DCAP QVL: Quote.cpp:209 - Attestation Key Type validation
	if quote.Header.AttestationKeyType != ECDSA_256_WITH_P256_CURVE {
		return false
	}

	// Based on Intel DCAP QVL: Quote.cpp:216 - TEE Type validation
	if quote.Header.TeeType != TEE_TYPE_SGX && quote.Header.TeeType != TEE_TYPE_TDX {
		return false
	}

	// Based on Intel DCAP QVL: Quote.cpp:222 - QE Vendor ID validation
	if quote.Header.QeVendorId != INTEL_QE_VENDOR_ID {
		return false
	}

	// TDX-specific version validation - TDX quotes must be v4 or v5
	if quote.Header.Version == QUOTE_VERSION_3 {
		if quote.Header.TeeType != TEE_TYPE_SGX {
			return false
		}
		if quote.QeCertificationData.CertificationDataType < 1 || quote.QeCertificationData.CertificationDataType > 5 {
			return false
		}
	}

	// Based on Intel DCAP QVL: Quote.cpp:242 - Quote v4/v5 validations
	if quote.Header.Version == QUOTE_VERSION_4 || quote.Header.Version == QUOTE_VERSION_5 {
		// Quote v4/v5 must use QE_REPORT_CERTIFICATION_DATA type (6)
		if quote.QeCertificationData.CertificationDataType != PCK_ID_QE_REPORT_CERTIFICATION_DATA {
			return false
		}

		// Additional validations for v4/v5 quotes with QE Report Certification Data
		if quote.Header.TeeType == TEE_TYPE_TDX {
			// Get QE Report Certification Data from interface
			qeReportCertData, ok := quote.QeCertificationData.CertificationData.(*QeReportCertificationData)
			if !ok {
				return false
			}

			// Check the QE Report certification data type (QVL: 1..5 allowed)
			if qeReportCertData.QeCertificationData.CertificationDataType < 1 ||
				qeReportCertData.QeCertificationData.CertificationDataType > 5 {
				return false
			}

		}

		// QVL: For Quote v5, validate body type and its compatibility with TEE type
		if quote.Header.Version == QUOTE_VERSION_5 {
			// V5 TDX specific validation - must have body descriptor
			if quote.BodyDescriptor == nil {
				return false
			}
			if quote.BodyDescriptor.TdQuoteBodyType != BODY_SGX_ENCLAVE_REPORT_TYPE &&
				quote.BodyDescriptor.TdQuoteBodyType != BODY_TD_REPORT10_TYPE &&
				quote.BodyDescriptor.TdQuoteBodyType != BODY_TD_REPORT15_TYPE {
				return false
			}
			// SGX must use SGX Enclave body; non-SGX must not use SGX Enclave body
			if quote.Header.TeeType == TEE_TYPE_SGX && quote.BodyDescriptor.TdQuoteBodyType != BODY_SGX_ENCLAVE_REPORT_TYPE {
				return false
			}
			if quote.Header.TeeType != TEE_TYPE_SGX && quote.BodyDescriptor.TdQuoteBodyType == BODY_SGX_ENCLAVE_REPORT_TYPE {
				return false
			}
		}
	}

	return true
}

// setQuoteSupplementalData sets supplemental data for quote verification result
// Based on Intel DCAP QVL: QuoteVerification/QvE/Enclave/qve.cpp:1097-1452 (qve_set_quote_supplemental_data)
func (qv *QuoteVerifier) setQuoteSupplementalData(tcbInfo *TcbInfo, qeIdentity *QeIdentity, certChain *EcdsaCertChain, quote *TdxEcdsaQuote, collateralDates *CollateralDates, crls []*x509.RevocationList) (*SupplementalData, error) {
	supplementalData := &SupplementalData{
		Version: 0x00030003, // Version 3.3 (From the reference Intel DCAP QVL version)
		TeeType: quote.Header.TeeType,
	}

	// Fill certificate and CRL information using pre-calculated dates from collateralDates
	// Based on Intel DCAP QVL: qve.cpp:1212-1217
	supplementalData.EarliestIssueDate = time.Unix(collateralDates.EarliestIssueDate, 0)
	supplementalData.LatestIssueDate = time.Unix(collateralDates.LatestIssueDate, 0)
	supplementalData.EarliestExpirationDate = time.Unix(collateralDates.EarliestExpirationDate, 0)
	// QE Identity specific dates
	if collateralDates.QeIdenEarliestIssueDate > 0 {
		supplementalData.QeIdentEarliestIssueDate = time.Unix(collateralDates.QeIdenEarliestIssueDate, 0)
	}
	if collateralDates.QeIdenLatestIssueDate > 0 {
		supplementalData.QeIdentLatestIssueDate = time.Unix(collateralDates.QeIdenLatestIssueDate, 0)
	}
	if collateralDates.QeIdenEarliestExpirationDate > 0 {
		supplementalData.QeIdentEarliestExpDate = time.Unix(collateralDates.QeIdenEarliestExpirationDate, 0)
	}

	// Set CRL sequence numbers as per DCAP QVL: qve.cpp:1313-1328
	if len(crls) >= 2 {
		// PCK CRL sequence number
		supplementalData.PckCrlNum = uint32(crls[1].Number.Int64())
		// Root CA CRL sequence number
		supplementalData.RootCaCrlNum = uint32(crls[0].Number.Int64())
	}

	// Set QE Identity status as per DCAP QVL: qve.cpp:1181-1183
	if qeIdentity != nil {
		// Reuse verification routines to reflect actual QE Identity status
		if status := qv.verifyQeIdentity(qeIdentity, quote); status != STATUS_OK {
			supplementalData.QeIdentStatus = status
		} else {
			supplementalData.QeIdentStatus = qv.verifyQeIdentityReport(qeIdentity, quote)
		}
	} else {
		supplementalData.QeIdentStatus = STATUS_OK
	}

	// Extract SGX extensions from PCK certificate
	_, pceId, err := ExtractSgxExtensions(certChain.PCKCert)
	if err != nil {
		return nil, fmt.Errorf("failed to extract SGX extensions: %w", err)
	}

	if len(pceId) >= 2 {
		supplementalData.PceId = bytesToUint16(pceId[:2])
	}

	// Extract CPU SVN from SGX extensions
	cpuSvn, err := ExtractCpuSvnFromSgxExtensions(certChain.PCKCert)
	if err != nil {
		return nil, fmt.Errorf("failed to extract CPU SVN from PCK certificate: %w", err)
	}

	// Fill CPU SVN from certificate
	if len(cpuSvn) >= 16 {
		copy(supplementalData.TcbCpusvn[:], cpuSvn[:16])
	}
	// Extract PCE ISVSVN
	if pceSvn, err := ExtractPceSvnFromSgxExtensions(certChain.PCKCert); err == nil {
		supplementalData.TcbPceIsvsvn = pceSvn
	}

	// Set TCB evaluation reference number from TCB info (QVL: tcbEvaluationDataNumber)
	supplementalData.TcbEvalRefNum = uint32(tcbInfo.TcbEvaluationDataNumber)

	// Set TCB level date tag from matching TCB level as per DCAP QVL: qve.cpp:1243-1244
	// Match TCB levels using the same logic as verification path
	if certChain != nil && certChain.PCKCert != nil && tcbInfo != nil {
		if pckTcb, err := qv.extractPckTcbFromCertificate(certChain.PCKCert); err == nil {
			var teeTcbSvn []byte
			isTdx := quote.Header.TeeType == TEE_TYPE_TDX && tcbInfo.Version >= 3 && (tcbInfo.ID == "TDX" || tcbInfo.ID == "SGX")
			if isTdx {
				if svn, err := qv.extractTeeTcbSvn(quote); err == nil {
					teeTcbSvn = svn
				}
			}
			if sgxLevel, tdxLevel, err := qv.matchTcbLevels(tcbInfo, pckTcb, teeTcbSvn); err == nil {
				var dateStr string
				if isTdx && tdxLevel != nil {
					dateStr = tdxLevel.TcbDate
				} else if sgxLevel != nil {
					dateStr = sgxLevel.TcbDate
				}
				if dateStr != "" {
					if t, err := time.Parse(time.RFC3339, dateStr); err == nil {
						supplementalData.TcbLevelDateTag = t
					}
				}
			}
		}
	}
	// QE Identity TCB level date tag（取第一个level的tcbDate）
	if qeIdentity != nil && len(qeIdentity.TcbLevels) > 0 {
		if t, err := time.Parse(time.RFC3339, qeIdentity.TcbLevels[0].TcbDate); err == nil {
			supplementalData.QeIdentTcbLevelDateTag = t
		}
		// QE Identity TCB evaluation reference number (QVL: tcbEvaluationDataNumber)
		supplementalData.QeIdentTcbEvalRefNum = uint32(qeIdentity.TcbEvaluationDataNumber)
	}

	// Extract platform instance ID from PCK certificate as per DCAP QVL: qve.cpp:1412-1419
	if certChain != nil && certChain.PCKCert != nil {
		if pid, err := ExtractPlatformInstanceIdFromCert(certChain.PCKCert); err == nil && len(pid) == 16 {
			copy(supplementalData.PlatformInstanceId[:], pid)
		} else {
			// keep zeroed when extension not present
			copy(supplementalData.PlatformInstanceId[:], make([]byte, 16))
		}
	}

	// Set SGX type based on quote version and TEE type
	if quote.Header.TeeType == TEE_TYPE_SGX {
		supplementalData.SgxType = 1 // Standard SGX
	} else {
		supplementalData.SgxType = 2 // TDX
	}

	// Set platform flags as per DCAP QVL: qve.cpp:1134-1138 (default values)
	// Extract configuration flags from PCK Certificate
	// Based on Intel DCAP QVL: QuoteVerification/QvE/Enclave/qve.cpp:1097-1452
	// Note: Many PCK certificates don't include configuration extensions (Dynamic Platform, Cached Keys, SMT Enabled)
	// This is expected behavior and these flags will remain as PCK_FLAG_UNDEFINED (0) in such cases
	if certChain != nil && certChain.PCKCert != nil {
		if pckFlags, err := ExtractPCKCertificateFlags(certChain.PCKCert); err == nil {
			supplementalData.DynamicPlatform = pckFlags.DynamicPlatform
			supplementalData.CachedKeys = pckFlags.CachedKeys
			supplementalData.SmtEnabled = pckFlags.SmtEnabled
		} else {
			// Fallback to undefined if extraction fails
			supplementalData.DynamicPlatform = 0 // PCK_FLAG_UNDEFINED
			supplementalData.CachedKeys = 0      // PCK_FLAG_UNDEFINED
			supplementalData.SmtEnabled = 0      // PCK_FLAG_UNDEFINED
		}
	} else {
		// Default values when no PCK certificate is available
		supplementalData.DynamicPlatform = 0 // PCK_FLAG_UNDEFINED
		supplementalData.CachedKeys = 0      // PCK_FLAG_UNDEFINED
		supplementalData.SmtEnabled = 0      // PCK_FLAG_UNDEFINED
	}

	// Build security advisories string from TCB info and QE Identity
	// Based on Intel DCAP QVL: QuoteVerification/QvE/Include/sgx_qve_header.h:133 (char sa_list[MAX_SA_LIST_SIZE])
	var allAdvisories []string

	// Collect advisories from TCB levels
	if len(tcbInfo.TcbLevels) > 0 {
		for _, level := range tcbInfo.TcbLevels {
			// Add specific advisory IDs if available
			allAdvisories = append(allAdvisories, level.AdvisoryIDs...)
		}
	}

	// Collect advisories from TDX Module TCB levels
	for _, tdxModuleIdentity := range tcbInfo.TdxModuleIdentities {
		for _, level := range tdxModuleIdentity.TcbLevels {
			allAdvisories = append(allAdvisories, level.AdvisoryIDs...)
		}
	}

	// Collect advisories from QE Identity TCB levels
	if qeIdentity != nil && len(qeIdentity.TcbLevels) > 0 {
		for _, level := range qeIdentity.TcbLevels {
			allAdvisories = append(allAdvisories, level.AdvisoryIDs...)
		}
	}

	// Remove duplicates and format as comma-separated string
	if len(allAdvisories) > 0 {
		uniqueAdvisories := make(map[string]bool)
		var finalAdvisories []string
		for _, advisory := range allAdvisories {
			if advisory != "" && !uniqueAdvisories[advisory] {
				uniqueAdvisories[advisory] = true
				finalAdvisories = append(finalAdvisories, advisory)
			}
		}
		if len(finalAdvisories) > 0 {
			supplementalData.SecurityAdvisories = strings.Join(finalAdvisories, ",")
		}
	}

	return supplementalData, nil
}

// packSupplementalData packs SupplementalData into a QVL 3.3-compatible byte buffer (little endian where applicable)
func (qv *QuoteVerifier) packSupplementalData(s *SupplementalData) ([]byte, error) {
	// The layout here follows a fixed order; all multi-byte integers are little endian.
	// time.Time fields are encoded as Unix(time_t) seconds (int64) per QVL usage of time_t.
	var buf bytes.Buffer
	writeU32 := func(v uint32) {
		_ = binary.Write(&buf, binary.LittleEndian, v)
	}
	writeU16 := func(v uint16) {
		_ = binary.Write(&buf, binary.LittleEndian, v)
	}
	writeU8 := func(v uint8) {
		_ = buf.WriteByte(v)
	}
	writeI64 := func(v int64) {
		_ = binary.Write(&buf, binary.LittleEndian, v)
	}
	writeBytes := func(b []byte) {
		_, _ = buf.Write(b)
	}

	// Version
	writeU32(s.Version)
	// Dates
	writeI64(s.EarliestIssueDate.Unix())
	writeI64(s.LatestIssueDate.Unix())
	writeI64(s.EarliestExpirationDate.Unix())
	writeI64(s.TcbLevelDateTag.Unix())
	// CRL numbers
	writeU32(s.PckCrlNum)
	writeU32(s.RootCaCrlNum)
	// TCB eval ref
	writeU32(s.TcbEvalRefNum)
	// Root key id (48)
	writeBytes(s.RootKeyId[:])
	// PCK PPID (16)
	writeBytes(s.PckPpid[:])
	// CPU SVN (16)
	writeBytes(s.TcbCpusvn[:])
	// PCE ISVSVN
	writeU16(s.TcbPceIsvsvn)
	// PCE ID
	writeU16(s.PceId)
	// TEE Type
	writeU32(s.TeeType)
	// SGX Type
	writeU8(s.SgxType)
	// Platform Instance ID (16)
	writeBytes(s.PlatformInstanceId[:])
	// Flags
	writeU8(s.DynamicPlatform)
	writeU8(s.CachedKeys)
	writeU8(s.SmtEnabled)
	// Security advisories (fixed 320 bytes, zero-padded)
	adv := []byte(s.SecurityAdvisories)
	if len(adv) > 320 {
		adv = adv[:320]
	}
	padded := make([]byte, 320)
	copy(padded, adv)
	writeBytes(padded)
	// QE Identity dates
	writeI64(s.QeIdentEarliestIssueDate.Unix())
	writeI64(s.QeIdentLatestIssueDate.Unix())
	writeI64(s.QeIdentEarliestExpDate.Unix())
	writeI64(s.QeIdentTcbLevelDateTag.Unix())
	// QE Identity eval ref
	writeU32(s.QeIdentTcbEvalRefNum)
	// QE Identity status (store as uint32)
	writeU32(uint32(s.QeIdentStatus))

	return buf.Bytes(), nil
}

// verifyCertificateSignatures verifies the certificate signatures in the chain
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/PckCertVerifier.cpp:98-224
// and CommonVerifier.cpp:106-109 (checkSignature function)
func (qv *QuoteVerifier) verifyCertificateSignatures(chain *EcdsaCertChain) Status {
	// Step 1: Verify Root CA (self-signed certificate)
	// Based on Intel DCAP QVL: CommonVerifier.cpp:71-86 (verifyRootCACert)
	if chain.RootCA == nil {
		return STATUS_SGX_ROOT_CA_MISSING // STATUS_SGX_ROOT_CA_MISSING = 2
	}

	// Verify root CA is self-signed
	if chain.RootCA.Subject.String() != chain.RootCA.Issuer.String() {
		return STATUS_SGX_ROOT_CA_INVALID_ISSUER
	}

	// Verify root CA self-signature
	// Based on Intel DCAP QVL: CommonVerifier.cpp:79-83
	if err := chain.RootCA.CheckSignatureFrom(chain.RootCA); err != nil {
		return STATUS_SGX_ROOT_CA_INVALID_ISSUER
	}

	// Step 2: Verify Intermediate CA signature against Root CA
	// Based on Intel DCAP QVL: CommonVerifier.cpp:88-103 (verifyIntermediate)
	intermediateCA := getIntermediateCert(chain)
	if intermediateCA == nil {
		return STATUS_SGX_INTERMEDIATE_CA_MISSING // STATUS_SGX_INTERMEDIATE_CA_MISSING = 7
	}

	// Verify intermediate CA is signed by root CA
	if intermediateCA.Issuer.String() != chain.RootCA.Subject.String() {
		return STATUS_SGX_INTERMEDIATE_CA_INVALID_ISSUER
	}

	// Verify intermediate CA signature
	// Based on Intel DCAP QVL: CommonVerifier.cpp:97-100
	if err := intermediateCA.CheckSignatureFrom(chain.RootCA); err != nil {
		return STATUS_SGX_INTERMEDIATE_CA_INVALID_ISSUER
	}

	// Step 3: Verify PCK Certificate signature against Intermediate CA
	// Based on Intel DCAP QVL: PckCertVerifier.cpp:205-221 (verifyPCKCert)
	if chain.PCKCert == nil {
		return STATUS_SGX_PCK_MISSING // STATUS_SGX_PCK_MISSING = 12
	}

	// Verify PCK certificate is signed by intermediate CA
	if chain.PCKCert.Issuer.String() != intermediateCA.Subject.String() {
		return STATUS_SGX_PCK_INVALID_ISSUER
	}

	// Verify PCK certificate signature
	// Based on Intel DCAP QVL: PckCertVerifier.cpp:214-218 and CommonVerifier.cpp:106-109
	if err := chain.PCKCert.CheckSignatureFrom(intermediateCA); err != nil {
		return STATUS_SGX_PCK_INVALID_ISSUER
	}

	return STATUS_OK
}

// verifyPckCertificateCN verifies PCK certificate CN contains required phrase
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:65-68
func (qv *QuoteVerifier) verifyPckCertificateCN(pckCert *x509.Certificate) Status {
	if pckCert == nil {
		return STATUS_INVALID_PCK_CERT
	}

	if !strings.Contains(pckCert.Subject.CommonName, SGX_PCK_CN_PHRASE) {
		return STATUS_INVALID_PCK_CERT
	}

	return STATUS_OK
}

// parsePckCrl parses the PCK CRL from the collateral and returns specific status
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:70-75
func (qv *QuoteVerifier) parsePckCrl(collateral *Collateral) (*x509.RevocationList, Status) {
	if len(collateral.PckCrl) == 0 {
		return nil, STATUS_UNSUPPORTED_PCK_RL_FORMAT
	}

	// Use the unified parseCrlBytes function to handle all formats
	pckCrl, err := qv.parseCrlBytes(collateral.PckCrl)
	if err != nil {
		return nil, STATUS_UNSUPPORTED_PCK_RL_FORMAT
	}

	return pckCrl, STATUS_OK
}

// verifyPckCrl verifies the PCK Certificate Revocation List and returns specific status
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:70-91
func (qv *QuoteVerifier) verifyPckCrl(pckCrl *x509.RevocationList, chain *EcdsaCertChain, quote *TdxEcdsaQuote, collateral *Collateral) Status {
	if collateral == nil {
		return STATUS_MISSING_PARAMETERS
	}
	// Check CRL expiration
	checkTime := time.Now()
	if pckCrl.NextUpdate.Before(checkTime) {
		return STATUS_SGX_CRL_EXPIRED // STATUS_SGX_CRL_EXPIRED = 79
	}

	// Verify PCK CRL signature using Intermediate CA certificate (QVL)
	// Based on Intel DCAP QVL: verify CRL signature against issuer
	intermediateCA := getIntermediateCert(chain)
	if intermediateCA == nil {
		return STATUS_SGX_INTERMEDIATE_CA_MISSING
	}
	if intermediateCA.Subject.String() != pckCrl.Issuer.String() {
		return STATUS_INVALID_PCK_CRL
	}
	if err := pckCrl.CheckSignatureFrom(intermediateCA); err != nil {
		return STATUS_INVALID_PCK_CRL
	}

	return STATUS_OK
}

// verifyPckCrlIssuer verifies the PCK CRL issuer matches the PCK certificate issuer
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:71-84
func (qv *QuoteVerifier) verifyPckCrlIssuer(crl *x509.RevocationList, pckCert *x509.Certificate) Status {
	if crl == nil {
		return STATUS_INVALID_PCK_CRL
	}

	if pckCert == nil {
		return STATUS_SGX_PCK_MISSING
	}

	// Verify CRL issuer CN contains required phrase
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/PckCrlVerifier.cpp checkIssuer method
	crlIssuerCN := crl.Issuer.CommonName
	if !strings.Contains(crlIssuerCN, SGX_INTERMEDIATE_CN_PHRASE) {
		return STATUS_INVALID_PCK_CRL
	}

	// Verify CRL issuer matches PCK certificate issuer
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:77-84
	if crl.Issuer.String() != pckCert.Issuer.String() {
		return STATUS_INVALID_PCK_CRL
	}

	return STATUS_OK
}

// checkPckCertificateRevocation checks if the PCK certificate is revoked by the CRL
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:87-91
func (qv *QuoteVerifier) checkPckCertificateRevocation(crl *x509.RevocationList, pckCert *x509.Certificate) Status {
	if crl == nil {
		return STATUS_INVALID_PCK_CRL
	}

	if pckCert == nil {
		return STATUS_SGX_PCK_MISSING
	}

	// Check if the certificate is in the revoked certificates list
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:87-91
	for _, revokedCert := range crl.RevokedCertificateEntries {
		if revokedCert.SerialNumber.Cmp(pckCert.SerialNumber) == 0 {
			fmt.Printf("DEBUG: PCK Certificate revoked by CRL in checkPckCertificateRevocation\n")
			return STATUS_SGX_PCK_REVOKED // STATUS_SGX_PCK_REVOKED = 16
		}
	}

	return STATUS_OK
}

// findTdxModuleIdentity finds TDX Module Identity based on version
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TdxModuleCheck.cpp:38-57
func (qv *QuoteVerifier) findTdxModuleIdentity(tdxModuleIdentities []TdxModuleIdentity, tdxModuleVersion uint8) *TdxModuleIdentity {
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:41
	tdxModuleIdentityId := fmt.Sprintf("TDX_%02X", tdxModuleVersion)

	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:43-51
	for i := range tdxModuleIdentities {
		// Convert to uppercase for comparison (matching QVL's std::transform)
		id := strings.ToUpper(tdxModuleIdentities[i].ID)
		if id == strings.ToUpper(tdxModuleIdentityId) {
			return &tdxModuleIdentities[i]
		}
	}

	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:52-57
	return nil
}

// checkTdxModuleTcbStatus gets TDX Module TCB status for use in TCB Level Check (4.1.2.4.17)
// This method extracts only the TCB status checking logic needed for 4.1.2.4.17
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TdxModuleCheck.cpp:62-97
func (qv *QuoteVerifier) checkTdxModuleTcbStatus(tcbInfo *TcbInfo, quote *TdxEcdsaQuote, tdxModuleIdentity *TdxModuleIdentity) Status {
	// Extract TDX Module version and ISVSVN from quote
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:66-67
	teeTcbSvn, err := qv.extractTeeTcbSvn(quote)
	if err != nil {
		return STATUS_TDX_MODULE_MISMATCH
	}
	tdxModuleVersion := teeTcbSvn[1]
	tdxModuleIsvSvn := teeTcbSvn[0]

	// Special case for quote version > 3 and TDX Module version 0
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:69-72
	if quote.Header.Version > 3 && tdxModuleVersion == 0 {
		return STATUS_OK
	}

	// Use provided tdxModuleIdentity or find it if not provided
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:73-81
	if tdxModuleIdentity == nil {
		tdxModuleIdentity = qv.findTdxModuleIdentity(tcbInfo.TdxModuleIdentities, tdxModuleVersion)
		if tdxModuleIdentity == nil {
			return STATUS_TDX_MODULE_MISMATCH
		}
	}

	// Find matching TDX Module TCB Level
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:83-93
	var tdxModuleTcbLevel *TdxModuleTcbLevel
	for i := range tdxModuleIdentity.TcbLevels {
		tcbLevel := &tdxModuleIdentity.TcbLevels[i]
		if tdxModuleIsvSvn >= uint8(tcbLevel.Tcb.IsvSvn) {
			tdxModuleTcbLevel = tcbLevel
			break
		}
	}

	if tdxModuleTcbLevel == nil {
		return STATUS_TCB_NOT_SUPPORTED
	}

	// Convert TCB status string to Status
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:96
	return stringToTcbStatus(tdxModuleTcbLevel.TcbStatus, ValidModuleTCBStatuses)
}

// verifyQeReportSignature verifies QE Report signature according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:221-227
func (qv *QuoteVerifier) verifyQeReportSignature(pckCert *x509.Certificate, quote *TdxEcdsaQuote, rawQuote []byte) Status {
	// Step 4.1.2.4.12.1: Extract public key from PCK certificate
	// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:221
	pckPublicKey := pckCert.PublicKey
	if pckPublicKey == nil {
		return STATUS_INVALID_PCK_CERT
	}

	// Step 4.1.2.4.12.2: Extract QE Report raw bytes (384 bytes) from original quote
	// Based on Intel DCAP QVL: copyAndAdvance(qeReport, from, ENCLAVE_REPORT_BYTE_LEN, end) in QuoteStructures.cpp:272
	qeReportBytes, err := ExtractQeReportBytes(rawQuote, quote)
	if err != nil {
		return STATUS_INVALID_QE_REPORT_SIGNATURE
	}

	// Step 4.1.2.4.12.3: Extract QE Report signature from parsed quote
	var qeReportSignature [64]byte
	if qeReportCertData, ok := quote.QeCertificationData.CertificationData.(*QeReportCertificationData); ok {
		qeReportSignature = qeReportCertData.QeReportSignature
	} else {
		return STATUS_INVALID_QE_REPORT_SIGNATURE
	}

	// Step 4.1.2.4.12.4: Verify QE Report signature using PCK certificate public key
	// Based on Intel DCAP QVL: crypto::verifySha256EcdsaSignature in QuoteVerifier.cpp:221
	ecdsaPublicKey, ok := pckPublicKey.(*ecdsa.PublicKey)
	if !ok {
		return STATUS_INVALID_PCK_CERT
	}

	if err := VerifyECDSASignature(ecdsaPublicKey, qeReportBytes, qeReportSignature[:]); err != nil {
		return STATUS_INVALID_QE_REPORT_SIGNATURE
	}

	return STATUS_OK
}

// verifyQeReportData verifies QE Report Data according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:229-248
func (qv *QuoteVerifier) verifyQeReportData(quote *TdxEcdsaQuote) Status {
	// Step 4.1.2.4.13.1: Extract AttestKeyData and QeAuthData from quote
	// Based on Intel DCAP QVL: quote.getAttestKeyData() and quote.getQeAuthData()
	var attestKeyData [64]byte
	var qeAuthData []byte
	var qeReportData [64]byte

	// Extract data from quote structure
	copy(attestKeyData[:], quote.EcdsaAttestationKey[:])

	// Extract QeAuthData and QeReport.reportData from nested structure
	if qeReportCertData, ok := quote.QeCertificationData.CertificationData.(*QeReportCertificationData); ok {
		qeAuthData = qeReportCertData.QeAuthenticationData
		qeReportData = qeReportCertData.QeReport.ReportData
	} else {
		return STATUS_INVALID_QE_REPORT_DATA
	}

	// Step 4.1.2.4.13.2: Concatenate AttestKeyData and QeAuthData
	// Based on Intel DCAP QVL: concatenation in QuoteVerifier.cpp:232-235
	concatenatedData := make([]byte, 0, len(attestKeyData)+len(qeAuthData))
	concatenatedData = append(concatenatedData, attestKeyData[:]...)
	concatenatedData = append(concatenatedData, qeAuthData...)

	// Step 4.1.2.4.13.3: Calculate SHA256 hash
	// Based on Intel DCAP QVL: crypto::sha256Digest(ret) in QuoteVerifier.cpp:237
	hash := sha256.Sum256(concatenatedData)

	// Step 4.1.2.4.13.4: Compare with QE Report's reportData
	// Based on Intel DCAP QVL: std::equal comparison in QuoteVerifier.cpp:240-242
	// The comparison is: std::equal(hash.begin(), hash.end(), reportData.begin())
	// where hash is 32 bytes (SHA256) and reportData is 64 bytes, so only first 32 bytes are compared
	if len(hash) != 32 {
		return STATUS_INVALID_QE_REPORT_DATA
	}

	// Compare SHA256 hash (32 bytes) with first 32 bytes of QE Report's reportData (64 bytes total)
	if len(qeReportData) < 32 {
		return STATUS_INVALID_QE_REPORT_DATA
	}

	for i := 0; i < 32; i++ {
		if hash[i] != qeReportData[i] {
			return STATUS_INVALID_QE_REPORT_DATA
		}
	}

	return STATUS_OK
}

// verifyQeIdentity verifies QE Identity according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:252-281
func (qv *QuoteVerifier) verifyQeIdentity(qeIdentity *QeIdentity, quote *TdxEcdsaQuote) Status {
	// Step 4.1.2.4.14.1: Check TEE type and QE Identity version/ID compatibility
	// Based on Intel DCAP QVL: QuoteVerifier.cpp:253-281
	teeType := quote.Header.TeeType

	if teeType == TEE_TYPE_TDX {
		// For TDX quotes
		if qeIdentity.Version == 1 {
			// Based on Intel DCAP QVL: QuoteVerifier.cpp:255-259
			return STATUS_QE_IDENTITY_MISMATCH
		} else if qeIdentity.Version == 2 {
			// Based on Intel DCAP QVL: QuoteVerifier.cpp:260-267
			if qeIdentity.ID != EnclaveIDTDQE {
				return STATUS_QE_IDENTITY_MISMATCH
			}
		}
	} else if teeType == TEE_TYPE_SGX {
		// For SGX quotes
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:269-276
		if qeIdentity.ID != EnclaveIDQE {
			return STATUS_QE_IDENTITY_MISMATCH
		}
	} else {
		// Unknown TEE type
		// Based on Intel DCAP QVL: QuoteVerifier.cpp:277-281
		return STATUS_QE_IDENTITY_MISMATCH
	}

	return STATUS_OK
}

// verifyQeIdentityReport verifies QE Identity Report according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/EnclaveReportVerifier.cpp:47-113
func (qv *QuoteVerifier) verifyQeIdentityReport(qeIdentity *QeIdentity, quote *TdxEcdsaQuote) Status {
	// Extract QE Report from quote
	var qeReport EnclaveReportBody
	if qeReportCertData, ok := quote.QeCertificationData.CertificationData.(*QeReportCertificationData); ok {
		qeReport = qeReportCertData.QeReport
	} else {
		return STATUS_UNSUPPORTED_QE_CERTIFICATION
	}

	// Step 4.1.2.9.5: MiscSelect verification
	// Based on Intel DCAP QVL: EnclaveReportVerifier.cpp:52-58
	miscSelectBytes, err := hex.DecodeString(qeIdentity.MiscSelect)
	if err != nil {
		return STATUS_SGX_ENCLAVE_REPORT_MISCSELECT_MISMATCH
	}
	miscSelectMaskBytes, err := hex.DecodeString(qeIdentity.MiscSelectMask)
	if err != nil {
		return STATUS_SGX_ENCLAVE_REPORT_MISCSELECT_MISMATCH
	}

	if len(miscSelectBytes) >= 4 && len(miscSelectMaskBytes) >= 4 {
		expectedMiscSelect := bytesToUint32(miscSelectBytes[:4])
		miscSelectMask := bytesToUint32(miscSelectMaskBytes[:4])

		if (qeReport.MiscSelect & miscSelectMask) != expectedMiscSelect {
			return STATUS_SGX_ENCLAVE_REPORT_MISCSELECT_MISMATCH
		}
	}

	// Step 4.1.2.9.6: Attributes verification
	// Based on Intel DCAP QVL: EnclaveReportVerifier.cpp:60-67
	attributesBytes, err := hex.DecodeString(qeIdentity.Attributes)
	if err != nil {
		return STATUS_SGX_ENCLAVE_REPORT_ATTRIBUTES_MISMATCH
	}
	attributesMaskBytes, err := hex.DecodeString(qeIdentity.AttributesMask)
	if err != nil {
		return STATUS_SGX_ENCLAVE_REPORT_ATTRIBUTES_MISMATCH
	}

	if len(attributesBytes) == 16 && len(attributesMaskBytes) == 16 {
		maskedAttributes := applyMask(qeReport.Attributes[:], attributesMaskBytes)
		if !bytes.Equal(maskedAttributes, attributesBytes) {
			return STATUS_SGX_ENCLAVE_REPORT_ATTRIBUTES_MISMATCH
		}
	}

	// Step 4.1.2.9.7: MrSigner verification
	// Based on Intel DCAP QVL: EnclaveReportVerifier.cpp:69-79
	if qeIdentity.MrSigner != "" {
		mrSignerBytes, err := hex.DecodeString(qeIdentity.MrSigner)
		if err != nil {
			return STATUS_SGX_ENCLAVE_IDENTITY_INVALID
		}

		if len(mrSignerBytes) == 32 && !bytes.Equal(qeReport.MrSigner[:], mrSignerBytes) {
			return STATUS_SGX_ENCLAVE_REPORT_MRSIGNER_MISMATCH
		}
	}

	// Step 4.1.2.9.8: IsvProdId verification
	// Based on Intel DCAP QVL: EnclaveReportVerifier.cpp:81-87
	if qeReport.IsvProdID != uint16(qeIdentity.IsvProdId) {
		return STATUS_SGX_ENCLAVE_REPORT_ISVPRODID_MISMATCH
	}

	// Step 4.1.2.9.9 & 4.1.2.9.10: TCB status verification
	// Based on Intel DCAP QVL: EnclaveReportVerifier.cpp:89-109
	tcbStatus, err := qv.getTcbStatusForIsvSvn(qeIdentity, qeReport.IsvSvn)
	if err != nil {
		return STATUS_SGX_ENCLAVE_REPORT_ISVSVN_NOT_SUPPORTED
	}

	switch tcbStatus {
	case TCB_STATUS_REVOKED:
		return STATUS_SGX_ENCLAVE_REPORT_ISVSVN_REVOKED
	case TCB_STATUS_OUT_OF_DATE:
		return STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE
	case TCB_STATUS_UP_TO_DATE:
		// Valid status
	default:
		return STATUS_SGX_ENCLAVE_REPORT_ISVSVN_NOT_SUPPORTED
	}

	return STATUS_OK
}

// getTcbStatusForIsvSvn gets the TCB status for a given ISV SVN from QE Identity
// Based on Intel DCAP QVL: EnclaveIdentityV2.cpp:getTcbStatus
func (qv *QuoteVerifier) getTcbStatusForIsvSvn(qeIdentity *QeIdentity, isvSvn uint16) (string, error) {
	// Find the matching TCB level for the given ISV SVN
	// Based on Intel DCAP QVL: EnclaveIdentityV2.cpp:getTcbStatus logic
	for _, tcbLevel := range qeIdentity.TcbLevels {
		if tcbLevel.Tcb.IsvSvn <= int(isvSvn) {
			return tcbLevel.TcbStatus, nil
		}
	}

	// If no matching TCB level found, return not supported
	return "", fmt.Errorf("no matching TCB level found for ISV SVN %d", isvSvn)
}

// verifyQuoteSignature verifies Quote signature according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp:305-320
func (qv *QuoteVerifier) verifyQuoteSignature(quote *TdxEcdsaQuote, rawQuote []byte) Status {
	// Step 4.1.2.4.16.1: Extract attestation key from quote
	// Based on Intel DCAP QVL: crypto::rawToP256PubKey(quote.getAttestKeyData()) in QuoteVerifier.cpp:305
	attestKeyData := quote.EcdsaAttestationKey // [64]byte

	// Convert raw key data to ECDSA public key
	publicKey, err := ParseECDSAPublicKey(attestKeyData[:])
	if err != nil {
		return STATUS_INVALID_QUOTE_SIGNATURE
	}

	// Step 4.1.2.4.16.2: Extract quote signature
	// Based on Intel DCAP QVL: quote.getQuoteSignature() in QuoteVerifier.cpp:312
	quoteSignature := quote.QuoteSignature // [64]byte

	// Step 4.1.2.4.16.3: Extract signed data from quote
	// Based on Intel DCAP QVL: quote.getSignedData() in QuoteVerifier.cpp:313
	signedData, err := ExtractQuoteSignedData(rawQuote)
	if err != nil {
		return STATUS_INVALID_QUOTE_SIGNATURE
	}

	// Step 4.1.2.4.16.4: Verify ECDSA signature
	// Based on Intel DCAP QVL: crypto::verifySha256EcdsaSignature() in QuoteVerifier.cpp:312-314
	if err := VerifyECDSASignature(publicKey, signedData, quoteSignature[:]); err != nil {
		return STATUS_INVALID_QUOTE_SIGNATURE
	}

	return STATUS_OK
}

// checkTcbLevel performs TCB Level check according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TcbLevelCheck.cpp:183-259
func (qv *QuoteVerifier) checkTcbLevel(tcbInfo *TcbInfo, pckCert *x509.Certificate, quote *TdxEcdsaQuote, qeIdentityStatus Status, tdxModuleIdentity *TdxModuleIdentity) Status {

	// Check TCB Info validity first - only reject nil TCB Info
	if tcbInfo == nil {
		return STATUS_UNSUPPORTED_TCB_INFO_FORMAT
	}

	// Check if this is TDX
	isTdx := tcbInfo.Version >= 3 &&
		tcbInfo.ID == "TDX" &&
		quote.Header.TeeType == TEE_TYPE_TDX

	// Extract PCK certificate TCB values
	pckTcb, err := qv.extractPckTcbFromCertificate(pckCert)
	if err != nil {
		return STATUS_INVALID_PCK_CERT
	}

	// Extract TEE TCB SVN for TDX
	var teeTcbSvn []byte
	if isTdx {
		var err error
		teeTcbSvn, err = qv.extractTeeTcbSvn(quote)
		if err != nil {
			return STATUS_TCB_NOT_SUPPORTED
		}
	}

	// Match TCB levels
	sgxTcbLevel, tdxTcbLevel, err := qv.matchTcbLevels(tcbInfo, pckTcb, teeTcbSvn)
	if err != nil {
		return STATUS_TCB_NOT_SUPPORTED
	}

	if sgxTcbLevel == nil {
		return STATUS_TCB_NOT_SUPPORTED
	}

	// Get SGX TCB status
	sgxTcbStatus := stringToTcbStatus(sgxTcbLevel.TcbStatus, ValidTCBInfoStatuses)
	// if sgxTcbStatus == STATUS_TCB_REVOKED {
	// logging error but not exit
	// }
	if !isTdx {
		// For SGX quotes, converge with QE Identity status
		if qeIdentityStatus != STATUS_OK {
			return qv.convergeTcbStatusWithQeTcbStatus(sgxTcbStatus, qeIdentityStatus)
		}
		return sgxTcbStatus
	}

	// TDX-specific processing
	if tdxTcbLevel == nil {
		return STATUS_TCB_NOT_SUPPORTED
	}

	// Check TDX Module TCB status (4.1.2.4.17.4.1)
	// Based on DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TcbLevelCheck.cpp:229-244
	tdxModuleTcbStatus := qv.checkTdxModuleTcbStatus(tcbInfo, quote, tdxModuleIdentity)
	if tdxModuleTcbStatus == STATUS_TCB_NOT_SUPPORTED ||
		tdxModuleTcbStatus == STATUS_TDX_MODULE_MISMATCH {
		return tdxModuleTcbStatus
	}

	// Get TDX TCB status and converge with TDX Module status
	tdxTcbStatus := qv.convergeTcbStatusWithTdxModuleStatus(stringToTcbStatus(tdxTcbLevel.TcbStatus, ValidTCBInfoStatuses), tdxModuleTcbStatus)
	if tdxTcbStatus == STATUS_TCB_REVOKED {
		return tdxTcbStatus
	}

	// 4.1.2.4.17.4.3
	// Based on DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TcbLevelCheck.cpp:246-251
	// TD relaunch advisory (TDX v1.5 only) with teeTcbSvn2
	switch body := quote.Report.(type) {
	case TdReport15:
		tdxTcbStatus = qv.checkForRelaunch(body.TeeTcbSvn2, tcbInfo, sgxTcbStatus, tdxTcbStatus, tdxModuleTcbStatus, qeIdentityStatus)
	}

	// Converge with QE Identity status if available
	if qeIdentityStatus != STATUS_OK {
		return qv.convergeTcbStatusWithQeTcbStatus(tdxTcbStatus, qeIdentityStatus)
	}
	return tdxTcbStatus
}

// checkForRelaunch applies TD relaunch advisory logic for TDX v1.5 based on teeTcbSvn2
// Returns updated TDX TCB status if relaunch is advised, otherwise returns input tdxTcbStatus
// Based on DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TDRelaunchCheck.cpp:52-143
func (qv *QuoteVerifier) checkForRelaunch(teeTcbSvn2 [16]byte, tcbInfo *TcbInfo, sgxTcbStatus Status, tdxTcbStatus Status, tdxModuleTcbStatus Status, qeTcbStatus Status) Status {
	// ifception, but that is a literal implementation from documentation
	if qeTcbStatus != STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE &&
		qeTcbStatus != STATUS_SGX_ENCLAVE_REPORT_ISVSVN_REVOKED &&
		qeTcbStatus != STATUS_SGX_ENCLAVE_REPORT_ISVSVN_NOT_SUPPORTED {
		if sgxTcbStatus == STATUS_OK ||
			sgxTcbStatus == STATUS_TCB_SW_HARDENING_NEEDED ||
			sgxTcbStatus == STATUS_TCB_CONFIGURATION_NEEDED ||
			sgxTcbStatus == STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED {
			// if (tdxTcbStatus in {OUT_OF_DATE, OUT_OF_DATE_CONFIG_NEEDED})
			if tdxTcbStatus == STATUS_TCB_OUT_OF_DATE ||
				tdxTcbStatus == STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED {
				if tdxModuleTcbStatus == STATUS_TCB_OUT_OF_DATE {
					// latest TCB level must exist
					if len(tcbInfo.TcbLevels) == 0 {
						return STATUS_TCB_NOT_SUPPORTED
					}
					latestTcbLevel := &tcbInfo.TcbLevels[0]
					if teeTcbSvn2[1] == 0 {
						if int(teeTcbSvn2[0]) >= latestTcbLevel.Tcb.TdxTcbComponents[0].Svn &&
							int(teeTcbSvn2[2]) >= latestTcbLevel.Tcb.TdxTcbComponents[2].Svn {
							if isConfigurationNeeded(sgxTcbStatus) ||
								isConfigurationNeeded(tdxTcbStatus) {
								return STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED
							} else {
								return STATUS_TCB_TD_RELAUNCH_ADVISED
							}
						}
					} else {
						tdxModuleIdentity2 := qv.findTdxModuleIdentity(tcbInfo.TdxModuleIdentities, teeTcbSvn2[1])
						if tdxModuleIdentity2 == nil {
							return STATUS_TDX_MODULE_MISMATCH
						}
						if len(tdxModuleIdentity2.TcbLevels) == 0 {
							return STATUS_TCB_NOT_SUPPORTED
						}
						latestModuleLevel := &tdxModuleIdentity2.TcbLevels[0]
						if int(teeTcbSvn2[0]) >= latestModuleLevel.Tcb.IsvSvn &&
							int(teeTcbSvn2[2]) >= latestTcbLevel.Tcb.TdxTcbComponents[2].Svn {
							if isConfigurationNeeded(sgxTcbStatus) ||
								isConfigurationNeeded(tdxTcbStatus) {
								return STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED
							} else {
								return STATUS_TCB_TD_RELAUNCH_ADVISED
							}
						}
					}
				}
			}
		}
	}
	return tdxTcbStatus
}

// extractPckTcbFromCertificate extracts TCB values from PCK certificate
// Based on Intel DCAP QVL: AttestationParsers/src/X509/PckCertificate.cpp:71-74 (getTcb)
func (qv *QuoteVerifier) extractPckTcbFromCertificate(cert *x509.Certificate) (*PckTcb, error) {
	// Use existing ExtractSgxExtensions function from utils.go
	fmspc, _, err := ExtractSgxExtensions(cert)
	if err != nil {
		return nil, fmt.Errorf("failed to extract SGX extensions: %w", err)
	}

	// Extract CPU SVN from certificate SGX extensions
	// Based on Intel DCAP QVL: AttestationLibrary/src/AttestationParsers/src/X509/Tcb.cpp:224-230
	cpuSvn, err := ExtractCpuSvnFromSgxExtensions(cert)
	if err != nil {
		return nil, fmt.Errorf("failed to extract CPU SVN from certificate: %w", err)
	}

	// Extract PCE SVN from certificate SGX extensions
	// Based on Intel DCAP QVL: AttestationLibrary/src/AttestationParsers/src/X509/Tcb.cpp:222
	pceSvn, err := ExtractPceSvnFromSgxExtensions(cert)
	if err != nil {
		return nil, fmt.Errorf("failed to extract PCE SVN from certificate: %w", err)
	}

	return &PckTcb{
		CpuSvn: cpuSvn,
		PceSvn: pceSvn,
		Fmspc:  fmspc,
	}, nil
}

// extractTeeTcbSvn extracts TEE TCB SVN from quote
// Based on Intel DCAP QVL: AttestationLibrary/src/QuoteVerification/Quote.cpp:348-365 (getTeeTcbSvn)
func (qv *QuoteVerifier) extractTeeTcbSvn(quote *TdxEcdsaQuote) ([]byte, error) {
	switch report := quote.Report.(type) {
	case TdReport10:
		return report.TeeTcbSvn[:], nil
	case TdReport15:
		return report.TeeTcbSvn[:], nil
	default:
		return nil, fmt.Errorf("unsupported report type for TEE TCB SVN extraction: %T", report)
	}
}

// matchTcbLevels matches TCB levels according to Intel DCAP QVL specification
func (qv *QuoteVerifier) matchTcbLevels(tcbInfo *TcbInfo, pckTcb *PckTcb, teeTcbSvn []byte) (*TcbLevel, *TcbLevel, error) {
	var sgxTcbLevel *TcbLevel
	var tdxTcbLevel *TcbLevel

	for i := range tcbInfo.TcbLevels {
		tcbLevel := &tcbInfo.TcbLevels[i]

		// Check if PCK TCB is higher or equal to this level
		cpuSvnMatch := qv.isCpuSvnHigherOrEqual(pckTcb.CpuSvn, tcbLevel.Tcb.SgxTcbComponents)
		pceSvnMatch := pckTcb.PceSvn >= uint16(tcbLevel.Tcb.PceSvn)

		if cpuSvnMatch && pceSvnMatch {

			// Select SGX TCB level (first matching level)
			if sgxTcbLevel == nil {
				sgxTcbLevel = tcbLevel
			}

			// For TDX, also check TEE TCB SVN
			if len(teeTcbSvn) > 0 {
				if qv.isTdxTcbHigherOrEqual(teeTcbSvn, tcbLevel.Tcb.TdxTcbComponents) {
					tdxTcbLevel = tcbLevel
					break // Found matching TDX level
				}
			} else {
				// For non-TDX or when no TEE TCB SVN, the SGX level is sufficient
				break
			}
		}
	}

	return sgxTcbLevel, tdxTcbLevel, nil
}

// convergeTcbStatusWithQeTcbStatus converges TCB status with QE TCB status
func (qv *QuoteVerifier) convergeTcbStatusWithQeTcbStatus(tcbStatus, qeTcbStatus Status) Status {
	// Based on Intel DCAP QVL: TcbLevelCheck.cpp:83-126
	if qeTcbStatus == STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE {
		switch tcbStatus {
		case STATUS_OK, STATUS_TCB_SW_HARDENING_NEEDED:
			return STATUS_TCB_OUT_OF_DATE
		case STATUS_TCB_CONFIGURATION_NEEDED, STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED:
			return STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED
		}
	}
	if qeTcbStatus == STATUS_SGX_ENCLAVE_REPORT_ISVSVN_REVOKED {
		return STATUS_TCB_REVOKED
	}
	if qeTcbStatus == STATUS_SGX_ENCLAVE_REPORT_ISVSVN_NOT_SUPPORTED {
		return STATUS_TCB_NOT_SUPPORTED
	}

	return tcbStatus
}

// convergeTcbStatusWithTdxModuleStatus converges TCB status with TDX Module status
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TdxModuleCheck.cpp:99-135
func (qv *QuoteVerifier) convergeTcbStatusWithTdxModuleStatus(tcbStatus, tdxModuleStatus Status) Status {
	// Handle TDX Module OutOfDate status
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:101-115
	if tdxModuleStatus == STATUS_TCB_OUT_OF_DATE {
		switch tcbStatus {
		case STATUS_OK, STATUS_TCB_SW_HARDENING_NEEDED:
			return STATUS_TCB_OUT_OF_DATE
		case STATUS_TCB_CONFIGURATION_NEEDED, STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED:
			return STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED
		}
	}

	// Handle TDX Module Revoked status
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:116-120
	if tdxModuleStatus == STATUS_TCB_REVOKED {
		return STATUS_TCB_REVOKED
	}

	// Return TCB Level status for other cases
	// Based on Intel DCAP QVL: TdxModuleCheck.cpp:122-134
	switch tcbStatus {
	case STATUS_TCB_OUT_OF_DATE,
		STATUS_TCB_REVOKED,
		STATUS_TCB_CONFIGURATION_NEEDED,
		STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED,
		STATUS_TCB_SW_HARDENING_NEEDED,
		STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED,
		STATUS_OK:
		return tcbStatus
	default:
		return STATUS_TCB_NOT_SUPPORTED
	}
}

// isCpuSvnHigherOrEqual checks if CPU SVN is higher or equal
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TcbLevelCheck.cpp:44-58 (isCpuSvnHigherOrEqual)
func (qv *QuoteVerifier) isCpuSvnHigherOrEqual(pckCpuSvn []byte, tcbComponents []SgxTcbComponent) bool {
	if len(pckCpuSvn) != 16 {
		return false
	}

	// If no TCB components specified, cannot match
	if len(tcbComponents) == 0 {
		return false
	}

	// Ensure we have 16 components
	if len(tcbComponents) != 16 {
		return false
	}

	for i := 0; i < 16; i++ {
		if pckCpuSvn[i] < byte(tcbComponents[i].Svn) {
			return false
		}
	}
	return true
}

// isTdxTcbHigherOrEqual checks if TDX TCB SVN is higher or equal
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TcbLevelCheck.cpp:61-80 (isTdxTcbHigherOrEqual)
func (qv *QuoteVerifier) isTdxTcbHigherOrEqual(teeTcbSvn []byte, tdxComponents []TdxTcbComponent) bool {
	if len(teeTcbSvn) != 16 {
		return false
	}

	// If no TDX components specified, cannot match
	if len(tdxComponents) == 0 {
		return false
	}

	// Ensure we have 16 components
	if len(tdxComponents) != 16 {
		return false
	}

	for i := 0; i < 16; i++ {
		if teeTcbSvn[i] < byte(tdxComponents[i].Svn) {
			return false
		}
	}
	return true
}

// validateCertChainLength validates certificate chain structure and length
// Based on Intel DCAP QVL: qve.cpp:1824-1830
func (qv *QuoteVerifier) validateCertChainLength(certChain *EcdsaCertChain) error {
	if certChain == nil {
		return fmt.Errorf("certificate chain is nil")
	}

	// Validate that we have exactly EXPECTED_CERTIFICATE_COUNT_IN_PCK_CHAIN certificates in the PCK chain
	// Expected: Root CA, Intermediate CA, PCK Certificate
	if len(certChain.Certificates) != EXPECTED_CERTIFICATE_COUNT_IN_PCK_CHAIN {
		return fmt.Errorf("invalid certificate chain length: expected %d, got %d", EXPECTED_CERTIFICATE_COUNT_IN_PCK_CHAIN, len(certChain.Certificates))
	}

	// Validate that all required certificate types are present
	if certChain.RootCA == nil {
		return fmt.Errorf("root CA certificate is missing")
	}
	if getIntermediateCert(certChain) == nil {
		return fmt.Errorf("intermediate CA certificate is missing")
	}
	if certChain.PCKCert == nil {
		return fmt.Errorf("PCK certificate is missing")
	}

	return nil
}

// parseAndCombineCrls checks PEM CRL and creates CRLs combined array
// Based on Intel DCAP QVL: qve.cpp:1832-1868 (check_pem_crl -> check_hex_crl -> byte_to_hexstring -> create crls array)
func (qv *QuoteVerifier) parseAndCombineCrls(collateral *Collateral) ([]*x509.RevocationList, error) {
	if collateral == nil {
		return nil, fmt.Errorf("collateral is nil")
	}

	// Create CRLs array with 2 elements: [root_ca_crl, pck_crl]
	// Based on DCAP QVL: qve.cpp:1858 std::array<const char*, 2> crls;
	crls := make([]*x509.RevocationList, 2)

	// Process Root CA CRL as per DCAP QVL: qve.cpp:1834-1842
	if len(collateral.RootCaCrl) > 0 {
		rootCaCrl, err := qv.parseCrlBytes(collateral.RootCaCrl)
		if err != nil || rootCaCrl == nil {
			return nil, fmt.Errorf("failed to parse Root CA CRL: %v", err)
		}
		crls[0] = rootCaCrl
	}

	// Process PCK CRL as per DCAP QVL: qve.cpp:1846-1854
	if len(collateral.PckCrl) > 0 {
		pckCrl, err := qv.parseCrlBytes(collateral.PckCrl)
		if err != nil || pckCrl == nil {
			return nil, fmt.Errorf("failed to parse PCK CRL: %v", err)
		}
		crls[1] = pckCrl
	}

	return crls, nil
}

// parseCrlBytes parses CRL bytes in various formats (PEM, Hex, DER) and returns x509.RevocationList
// Based on Intel DCAP QVL: qve.cpp:320-348 (check_pem_crl -> check_hex_crl -> byte_to_hexstring)
func (qv *QuoteVerifier) parseCrlBytes(crlBytes []byte) (*x509.RevocationList, error) {
	if len(crlBytes) == 0 {
		return nil, fmt.Errorf("empty CRL data")
	}

	crlStr := string(crlBytes)

	// Check PEM format as per DCAP QVL: qve.cpp:320-329 (check_pem_crl)
	if strings.HasPrefix(crlStr, "-----BEGIN X509 CRL-----") {
		block, _ := pem.Decode(crlBytes)
		if block == nil || block.Type != "X509 CRL" {
			return nil, fmt.Errorf("invalid PEM CRL format")
		}
		return x509.ParseRevocationList(block.Bytes)
	}

	// Check hex format as per DCAP QVL: qve.cpp:335-348 (check_hex_crl)
	// Remove null terminator if present
	if len(crlStr) > 0 && crlStr[len(crlStr)-1] == 0 {
		crlStr = crlStr[:len(crlStr)-1]
	}

	// Try to decode as hex string
	if hexBytes, err := hex.DecodeString(crlStr); err == nil {
		return x509.ParseRevocationList(hexBytes)
	}

	// Convert DER to hex format as per DCAP QVL: qve.cpp:1837 (byte_to_hexstring)
	// Try parsing as DER directly
	if crl, err := x509.ParseRevocationList(crlBytes); err == nil {
		return crl, nil
	}

	return nil, fmt.Errorf("unsupported CRL format")
}

// getCollateralDates extracts issue and expiration dates from all collateral components
// Based on Intel DCAP QVL: qve.cpp:747-912 (qve_get_collateral_dates function)
func (qv *QuoteVerifier) getCollateralDates(certChain *EcdsaCertChain, tcbInfo *TcbInfo, qeIdentity *QeIdentity, collateral *Collateral, crls []*x509.RevocationList) (*CollateralDates, QuoteErrType) {
	// Parameter validation as per DCAP QVL: qve.cpp:758-772
	if certChain == nil || collateral == nil {
		return nil, SGX_QL_ERROR_INVALID_PARAMETER
	}

	// Check CRLs array as per DCAP QVL: qve.cpp:768-770
	if crls == nil || len(crls) < 2 {
		return nil, SGX_QL_ERROR_INVALID_PARAMETER
	}

	// Initialize result structure
	result := &CollateralDates{}

	// Initialize dates as per DCAP QVL: qve.cpp:773-779
	earliestIssueDate := int64(0)
	earliestExpirationDate := int64(0)
	latestIssueDate := int64(0)
	latestExpirationDate := int64(0)
	qeIdenEarliestIssueDate := int64(0)
	qeIdenLatestIssueDate := int64(0)
	qeIdenEarliestExpirationDate := int64(0)

	// Parse additional certificate chains as per DCAP QVL: qve.cpp:781-790
	// Parse QE Identity issuer chain
	var qeIdentityIssuerChain *EcdsaCertChain
	if len(collateral.QeIdentityIssuerChain) > 0 {
		var err error
		qeIdentityIssuerChain, err = ParseCertChain(collateral.QeIdentityIssuerChain)
		if err != nil || qeIdentityIssuerChain == nil {
			return nil, SGX_QL_PCK_CERT_CHAIN_ERROR
		}
	}

	// Parse TCB Info issuer chain
	var tcbInfoIssuerChain *EcdsaCertChain
	if len(collateral.TcbInfoIssuerChain) > 0 {
		var err error
		tcbInfoIssuerChain, err = ParseCertChain(collateral.TcbInfoIssuerChain)
		if err != nil || tcbInfoIssuerChain == nil {
			return nil, SGX_QL_PCK_CERT_CHAIN_ERROR
		}
	}

	//supports only EnclaveIdentity v2 and v3
	version := qeIdentity.Version
	if version != 2 && version != 3 {
		return nil, SGX_QL_QEIDENTITY_UNSUPPORTED_FORMAT
	}

	//supports only TcbInfo v2 and v3
	version = tcbInfo.Version
	if version != 2 && version != 3 {
		return nil, SGX_QL_TCBINFO_UNSUPPORTED_FORMAT
	}

	// CRLs are already parsed by parseAndCombineCrls as per DCAP QVL: qve.cpp:819-829
	rootCaCrl := crls[0]
	pckCrl := crls[1]

	// Parse PCK CRL issuer chain
	var pckCrlIssuerChain *EcdsaCertChain
	if len(collateral.PckCrlIssuerChain) > 0 {
		var err error
		pckCrlIssuerChain, err = ParseCertChain(collateral.PckCrlIssuerChain)
		if err != nil || pckCrlIssuerChain == nil {
			return nil, SGX_QL_PCK_CERT_CHAIN_ERROR
		}
	}

	// Earliest issue date
	// std::array<time_t, 8> earliest_issue, earliest_expiration, latest_issue, latest_expiration
	var earliestIssue [8]int64
	var earliestExpiration [8]int64
	var latestIssue [8]int64
	var latestExpiration [8]int64

	// Fill arrays as per DCAP QVL: qve.cpp:844-877
	// 0. Root CA CRL dates (qve.cpp:844-845)
	earliestIssue[0] = rootCaCrl.ThisUpdate.Unix()
	earliestExpiration[0] = rootCaCrl.NextUpdate.Unix()
	latestIssue[0] = rootCaCrl.ThisUpdate.Unix()
	latestExpiration[0] = rootCaCrl.NextUpdate.Unix()

	// 1. PCK CRL dates (qve.cpp:845-846)
	earliestIssue[1] = pckCrl.ThisUpdate.Unix()
	earliestExpiration[1] = pckCrl.NextUpdate.Unix()
	latestIssue[1] = pckCrl.ThisUpdate.Unix()
	latestExpiration[1] = pckCrl.NextUpdate.Unix()

	// 2. PCK CRL issuer chain dates (qve.cpp:846-847)
	dates := getCertChainDates(pckCrlIssuerChain)
	earliestIssue[2] = dates.earliestIssue
	earliestExpiration[2] = dates.earliestExpiration
	latestIssue[2] = dates.latestIssue
	latestExpiration[2] = dates.latestExpiration

	// 3. PCK certificate chain dates (qve.cpp:847-848)
	dates = getCertChainDates(certChain)
	earliestIssue[3] = dates.earliestIssue
	earliestExpiration[3] = dates.earliestExpiration
	latestIssue[3] = dates.latestIssue
	latestExpiration[3] = dates.latestExpiration

	// 4. TCB Info issuer chain dates (qve.cpp:848-849)
	dates = getCertChainDates(tcbInfoIssuerChain)
	earliestIssue[4] = dates.earliestIssue
	earliestExpiration[4] = dates.earliestExpiration
	latestIssue[4] = dates.latestIssue
	latestExpiration[4] = dates.latestExpiration

	// 5. QE Identity issuer chain dates (qve.cpp:849-850)
	dates = getCertChainDates(qeIdentityIssuerChain)
	earliestIssue[5] = dates.earliestIssue
	earliestExpiration[5] = dates.earliestExpiration
	latestIssue[5] = dates.latestIssue
	latestExpiration[5] = dates.latestExpiration
	// Set QE Identity specific dates as per DCAP QVL: qve.cpp:896-898
	qeIdenEarliestIssueDate = dates.earliestIssue
	qeIdenLatestIssueDate = dates.latestIssue
	qeIdenEarliestExpirationDate = dates.earliestExpiration

	// 6. TCB Info dates (qve.cpp:850-851)
	if issueDate, err := time.Parse(time.RFC3339, tcbInfo.IssueDate); err == nil {
		earliestIssue[6] = issueDate.Unix()
		latestIssue[6] = issueDate.Unix()
	}
	// Parse next update date
	if nextUpdate, err := time.Parse(time.RFC3339, tcbInfo.NextUpdate); err == nil {
		earliestExpiration[6] = nextUpdate.Unix()
		latestExpiration[6] = nextUpdate.Unix()
	}

	// 7. QE Identity dates (qve.cpp:851-852)
	if issueDate, err := time.Parse(time.RFC3339, qeIdentity.IssueDate); err == nil {
		earliestIssue[7] = issueDate.Unix()
		latestIssue[7] = issueDate.Unix()
	}
	// Parse next update date
	if nextUpdate, err := time.Parse(time.RFC3339, qeIdentity.NextUpdate); err == nil {
		earliestExpiration[7] = nextUpdate.Unix()
		latestExpiration[7] = nextUpdate.Unix()
	}

	// Calculate min/max dates as per DCAP QVL: qve.cpp:882-894
	// *p_earliest_issue_date = *std::min_element(earliest_issue.begin(), earliest_issue.end())
	earliestIssueDate = minElement(earliestIssue[:])
	earliestExpirationDate = minElement(earliestExpiration[:])
	latestIssueDate = maxElement(latestIssue[:])
	latestExpirationDate = maxElement(latestExpiration[:])

	// Validate that we have valid dates as per DCAP QVL: qve.cpp:900-906
	if earliestIssueDate == 0 || earliestExpirationDate == 0 || latestIssueDate == 0 || latestExpirationDate == 0 ||
		qeIdenEarliestIssueDate == 0 || qeIdenLatestIssueDate == 0 || qeIdenEarliestExpirationDate == 0 {
		return nil, SGX_QL_ERROR_UNEXPECTED
	}

	// Set result structure
	result.EarliestIssueDate = earliestIssueDate
	result.EarliestExpirationDate = earliestExpirationDate
	result.LatestIssueDate = latestIssueDate
	result.LatestExpirationDate = latestExpirationDate
	result.QeIdenEarliestIssueDate = qeIdenEarliestIssueDate
	result.QeIdenLatestIssueDate = qeIdenLatestIssueDate
	result.QeIdenEarliestExpirationDate = qeIdenEarliestExpirationDate

	return result, SGX_QL_SUCCESS
}

// extractChainFromQuote extracts the certificate chain from the quote (QVL extract_chain_from_quote)
func extractChainFromQuote(quote *TdxEcdsaQuote) (*EcdsaCertChain, QuoteErrType) {
	if quote == nil {
		return nil, SGX_QL_PCK_CERT_UNSUPPORTED_FORMAT
	}

	qeReportCertData, ok := quote.QeCertificationData.CertificationData.(*QeReportCertificationData)
	if !ok {
		return nil, SGX_QL_PCK_CERT_UNSUPPORTED_FORMAT
	}

	// Inner certification data must be PCK cert chain (type 5)
	if qeReportCertData.QeCertificationData.CertificationDataType != PCK_ID_PCK_CERT_CHAIN {
		return nil, SGX_QL_PCK_CERT_UNSUPPORTED_FORMAT
	}

	certDataBytes, ok := qeReportCertData.QeCertificationData.CertificationData.([]byte)
	if !ok || len(certDataBytes) == 0 {
		return nil, SGX_QL_PCK_CERT_UNSUPPORTED_FORMAT
	}

	chain, err := ParseCertChain(certDataBytes)
	if err != nil {
		return nil, SGX_QL_PCK_CERT_UNSUPPORTED_FORMAT
	}

	return chain, SGX_QL_SUCCESS
}

// stringToTcbStatus converts TCB status string to Status according to Intel DCAP QVL specification
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/TcbStatus.h:97-113 (stringToTcbStatus)
func stringToTcbStatus(tcbStatus string, validStatuses map[string]bool) Status {
	// Validate that the status is in the valid statuses set as per DCAP QVL: TcbStatus.h:99-103
	if !validStatuses[tcbStatus] {
		return STATUS_TCB_UNRECOGNIZED_STATUS
	}

	// Direct mapping from string to Status using TCB_STATUS_MAP as per DCAP QVL: TcbStatus.h:87-95
	// Based on Intel DCAP QVL: TcbStatus.h:105-112 (TCB_STATUS_MAP.find)
	if status, exists := TCB_STATUS_MAP[tcbStatus]; exists {
		return status
	}

	// This should not happen if validStatuses is properly set, but handle gracefully
	return STATUS_TCB_UNRECOGNIZED_STATUS
}

// statusToQuoteErr maps internal Status to quote3_error_t (QuoteErrType) as per DCAP QVL specification
// Based on Intel DCAP QVL: QuoteVerification/QvE/Enclave/qve.cpp:170-266 (status_error_to_quote3_error)
func statusToQuoteErr(s Status) QuoteErrType {
	switch s {
	case STATUS_OK, STATUS_TCB_TD_RELAUNCH_ADVISED, STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED:
		return SGX_QL_SUCCESS
	case STATUS_MISSING_PARAMETERS:
		return SGX_QL_ERROR_INVALID_PARAMETER
	case STATUS_UNSUPPORTED_QUOTE_FORMAT:
		return SGX_QL_QUOTE_FORMAT_UNSUPPORTED
	case STATUS_INVALID_QE_REPORT_SIGNATURE:
		return SGX_QL_QE_REPORT_INVALID_SIGNATURE
	case STATUS_SGX_ENCLAVE_REPORT_UNSUPPORTED_FORMAT:
		return SGX_QL_QE_REPORT_UNSUPPORTED_FORMAT
	case STATUS_UNSUPPORTED_PCK_CERT_FORMAT, STATUS_UNSUPPORTED_CERT_FORMAT:
		return SGX_QL_PCK_CERT_UNSUPPORTED_FORMAT
	case STATUS_INVALID_PCK_CERT, STATUS_SGX_PCK_CERT_CHAIN_UNTRUSTED, STATUS_SGX_ROOT_CA_UNTRUSTED:
		return SGX_QL_PCK_CERT_CHAIN_ERROR
	case STATUS_UNSUPPORTED_TCB_INFO_FORMAT, STATUS_SGX_TCB_INFO_UNSUPPORTED_FORMAT, STATUS_SGX_TCB_INFO_INVALID:
		return SGX_QL_TCBINFO_UNSUPPORTED_FORMAT
	case STATUS_TCB_NOT_SUPPORTED:
		return SGX_QL_TCB_NOT_SUPPORTED
	case STATUS_TCB_INFO_MISMATCH:
		return SGX_QL_TCBINFO_MISMATCH
	case STATUS_SGX_QE_IDENTITY_UNSUPPORTED_FORMAT:
		return SGX_QL_QEIDENTITY_UNSUPPORTED_FORMAT
	case STATUS_SGX_QE_IDENTITY_INVALID, STATUS_QE_IDENTITY_MISMATCH, STATUS_SGX_ENCLAVE_REPORT_MISCSELECT_MISMATCH, STATUS_SGX_ENCLAVE_REPORT_ATTRIBUTES_MISMATCH, STATUS_SGX_ENCLAVE_REPORT_MRENCLAVE_MISMATCH, STATUS_SGX_ENCLAVE_REPORT_MRSIGNER_MISMATCH, STATUS_SGX_ENCLAVE_REPORT_ISVPRODID_MISMATCH:
		return SGX_QL_QEIDENTITY_MISMATCH
	case STATUS_TCB_OUT_OF_DATE:
		return SGX_QL_TCB_OUT_OF_DATE
	case STATUS_TCB_CONFIGURATION_NEEDED:
		return SGX_QL_TCB_CONFIGURATION_NEEDED
	case STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED:
		return SGX_QL_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED
	case STATUS_SGX_ENCLAVE_IDENTITY_OUT_OF_DATE:
		return SGX_QL_SGX_ENCLAVE_IDENTITY_OUT_OF_DATE
	case STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE:
		return SGX_QL_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE
	case STATUS_QE_IDENTITY_OUT_OF_DATE:
		return SGX_QL_QE_IDENTITY_OUT_OF_DATE
	case STATUS_SGX_TCB_INFO_EXPIRED:
		return SGX_QL_SGX_TCB_INFO_EXPIRED
	case STATUS_SGX_PCK_CERT_CHAIN_EXPIRED:
		return SGX_QL_SGX_PCK_CERT_CHAIN_EXPIRED
	case STATUS_SGX_CRL_EXPIRED:
		return SGX_QL_SGX_CRL_EXPIRED
	case STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED:
		return SGX_QL_SGX_SIGNING_CERT_CHAIN_EXPIRED
	case STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED:
		return SGX_QL_SGX_ENCLAVE_IDENTITY_EXPIRED
	case STATUS_PCK_REVOKED, STATUS_SGX_PCK_REVOKED, STATUS_SGX_INTERMEDIATE_CA_REVOKED, STATUS_SGX_TCB_SIGNING_CERT_REVOKED:
		return SGX_QL_PCK_REVOKED
	case STATUS_TCB_REVOKED, STATUS_SGX_ENCLAVE_REPORT_ISVSVN_REVOKED:
		return SGX_QL_TCB_REVOKED
	case STATUS_UNSUPPORTED_QE_CERTIFICATION, STATUS_UNSUPPORTED_QE_CERTIFICATION_DATA_TYPE:
		return SGX_QL_QUOTE_CERTIFICATION_DATA_UNSUPPORTED
	case STATUS_SGX_ENCLAVE_IDENTITY_UNSUPPORTED_FORMAT, STATUS_SGX_ENCLAVE_IDENTITY_UNSUPPORTED_VERSION, STATUS_UNSUPPORTED_QE_IDENTITY_FORMAT, STATUS_SGX_ENCLAVE_IDENTITY_INVALID_SIGNATURE:
		return SGX_QL_QEIDENTITY_CHAIN_ERROR
	case STATUS_TCB_INFO_INVALID_SIGNATURE, STATUS_SGX_TCB_SIGNING_CERT_CHAIN_UNTRUSTED:
		return SGX_QL_TCBINFO_CHAIN_ERROR
	case STATUS_TCB_SW_HARDENING_NEEDED:
		return SGX_QL_TCB_SW_HARDENING_NEEDED
	case STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED:
		return SGX_QL_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED
	case STATUS_TDX_MODULE_MISMATCH:
		return SGX_QL_TDX_MODULE_MISMATCH
	case STATUS_INVALID_QUOTE_SIGNATURE, STATUS_SGX_CRL_INVALID_SIGNATURE, STATUS_SGX_QE_IDENTITY_INVALID_SIGNATURE:
		return SGX_QL_RESULT_INVALID_SIGNATURE
	default:
		return SGX_QL_ERROR_UNEXPECTED
	}
}

func statusToQvResult(s Status) QvResultType {
	switch s {
	case STATUS_OK:
		return SGX_QL_QV_RESULT_OK

	// Invalid signature bucket
	case STATUS_INVALID_QUOTE_SIGNATURE,
		STATUS_INVALID_QE_REPORT_SIGNATURE,
		STATUS_SGX_ENCLAVE_IDENTITY_INVALID_SIGNATURE,
		STATUS_SGX_QE_IDENTITY_INVALID_SIGNATURE,
		STATUS_SGX_CRL_INVALID_SIGNATURE,
		STATUS_TCB_INFO_INVALID_SIGNATURE:
		return SGX_QL_QV_RESULT_INVALID_SIGNATURE

	// Revoked bucket
	case STATUS_PCK_REVOKED,
		STATUS_TCB_REVOKED,
		STATUS_SGX_TCB_SIGNING_CERT_REVOKED,
		STATUS_SGX_PCK_REVOKED,
		STATUS_SGX_INTERMEDIATE_CA_REVOKED:
		return SGX_QL_QV_RESULT_REVOKED

	// Config needed
	case STATUS_TCB_CONFIGURATION_NEEDED:
		return SGX_QL_QV_RESULT_CONFIG_NEEDED

	// Out of date + config needed
	case STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED:
		return SGX_QL_QV_RESULT_OUT_OF_DATE_CONFIG_NEEDED

	// Out of date bucket
	case STATUS_TCB_OUT_OF_DATE,
		STATUS_SGX_ENCLAVE_IDENTITY_OUT_OF_DATE,
		STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE,
		STATUS_QE_IDENTITY_OUT_OF_DATE:
		return SGX_QL_QV_RESULT_OUT_OF_DATE

	// SW hardening needed
	case STATUS_TCB_SW_HARDENING_NEEDED:
		return SGX_QL_QV_RESULT_SW_HARDENING_NEEDED

	// Config + SW hardening needed
	case STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED:
		return SGX_QL_QV_RESULT_CONFIG_AND_SW_HARDENING_NEEDED

	// TD relaunch advisories (TDX v5.2)
	case STATUS_TCB_TD_RELAUNCH_ADVISED:
		return TEE_QV_RESULT_TD_RELAUNCH_ADVISED
	case STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED:
		return TEE_QV_RESULT_TD_RELAUNCH_ADVISED_CONFIG_NEEDED

	default:
		return SGX_QL_QV_RESULT_UNSPECIFIED
	}
}

// isConfigurationNeeded returns whether a status indicates configuration needed
// Based on DCAP QVL: AttestationLibrary/src/Verifiers/Checks/TDRelaunchCheck.cpp:39-49
func isConfigurationNeeded(status Status) bool {
	switch status {
	case STATUS_TCB_CONFIGURATION_NEEDED,
		STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED,
		STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED,
		STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED:
		return true
	default:
		return false
	}
}

// isNonterminalError checks if the status is non-terminal (allows success return)
// Based on Intel DCAP QVL: qve.cpp:115-137 (is_nonterminal_error function)
func isNonTerminalError(status Status) bool {
	switch status {
	case STATUS_TCB_OUT_OF_DATE,
		STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED,
		STATUS_SGX_ENCLAVE_IDENTITY_OUT_OF_DATE,
		STATUS_SGX_ENCLAVE_REPORT_ISVSVN_OUT_OF_DATE,
		STATUS_QE_IDENTITY_OUT_OF_DATE,
		STATUS_SGX_TCB_INFO_EXPIRED,
		STATUS_SGX_PCK_CERT_CHAIN_EXPIRED,
		STATUS_SGX_CRL_EXPIRED,
		STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED,
		STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED,
		STATUS_TCB_CONFIGURATION_NEEDED,
		STATUS_TCB_SW_HARDENING_NEEDED,
		STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED,
		STATUS_TCB_TD_RELAUNCH_ADVISED,
		STATUS_TCB_TD_RELAUNCH_ADVISED_CONFIGURATION_NEEDED:
		return true
	default:
		return false
	}
}

// isExpirationError checks if the status indicates an expiration error
// Based on Intel DCAP QVL: qve.cpp:148-160 (is_expiration_error function)
func isExpirationError(status Status) bool {
	switch status {
	case STATUS_SGX_TCB_INFO_EXPIRED,
		STATUS_SGX_PCK_CERT_CHAIN_EXPIRED,
		STATUS_SGX_CRL_EXPIRED,
		STATUS_SGX_SIGNING_CERT_CHAIN_EXPIRED,
		STATUS_SGX_ENCLAVE_IDENTITY_EXPIRED:
		return true
	default:
		return false
	}
}
