// 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 (
	"crypto/x509"
	"encoding/asn1"
	"encoding/json"
	"time"
)

// ------------------------------------------------------------
// TDX quote types
// ------------------------------------------------------------

// QuoteHeader is the header of an SGX/TDX quote compatible with v4 of the TrustedPlatform API
// Based on Intel DCAP QVL: QuoteHeader structure
type QuoteHeader struct {
	Version            uint16   // Quote version (DCAP QVL: version)
	AttestationKeyType uint16   // Attestation key type (DCAP QVL: attestationKeyType)
	TeeType            uint32   // TEE type: 0x0 = SGX, 0x81 = TDX (DCAP QVL: teeType)
	QeSvn              uint16   // QE security version number (DCAP QVL: qeSvn)
	PceSvn             uint16   // PCE security version number (DCAP QVL: pceSvn)
	QeVendorId         [16]byte // QE vendor ID (DCAP QVL: qeVendorId)
	UserData           [20]byte // User data (DCAP QVL: userData)
}

// EnclaveReportBody represents the SGX enclave report body
// Based on Intel DCAP QVL: SGX Enclave Report structure
type EnclaveReportBody struct {
	CpuSvn     [16]byte // CPU SVN (DCAP QVL: cpuSvn)
	MiscSelect uint32   // Miscellaneous select (DCAP QVL: miscSelect)
	Reserved1  [28]byte // Reserved field
	Attributes [16]byte // Enclave attributes (DCAP QVL: attributes)
	MrEnclave  [32]byte // Enclave measurement (DCAP QVL: mrEnclave)
	Reserved2  [32]byte // Reserved field
	MrSigner   [32]byte // Signer measurement (DCAP QVL: mrSigner)
	Reserved3  [96]byte // Reserved field
	IsvProdID  uint16   // ISV product ID (DCAP QVL: isvProdID)
	IsvSvn     uint16   // ISV security version number (DCAP QVL: isvSvn)
	Reserved4  [60]byte // Reserved field
	ReportData [64]byte // Report data (DCAP QVL: reportData)
}

// TdReport10 represents the TD report version 1.0
// Based on Intel DCAP QVL: TD Report 1.0 structure
type TdReport10 struct {
	TeeTcbSvn      [16]byte // TEE TCB SVN (DCAP QVL: teeTcbSvn)
	MrSeam         [48]byte // SEAM measurement (DCAP QVL: mrSeam)
	MrSignerSeam   [48]byte // SEAM signer measurement (DCAP QVL: mrSignerSeam)
	SeamAttributes [8]byte  // SEAM attributes (DCAP QVL: seamAttributes)
	TdAttributes   [8]byte  // TD attributes (DCAP QVL: tdAttributes)
	XFAM           [8]byte  // Extended features available mask (DCAP QVL: xFAM)
	MrTd           [48]byte // TD measurement (DCAP QVL: mrTd)
	MrConfigId     [48]byte // Configuration measurement (DCAP QVL: mrConfigId)
	MrOwner        [48]byte // Owner measurement (DCAP QVL: mrOwner)
	MrOwnerConfig  [48]byte // Owner configuration measurement (DCAP QVL: mrOwnerConfig)
	Rtmr0          [48]byte // Runtime measurement register 0 (DCAP QVL: rtMr0)
	Rtmr1          [48]byte // Runtime measurement register 1 (DCAP QVL: rtMr1)
	Rtmr2          [48]byte // Runtime measurement register 2 (DCAP QVL: rtMr2)
	Rtmr3          [48]byte // Runtime measurement register 3 (DCAP QVL: rtMr3)
	ReportData     [64]byte // Report data (DCAP QVL: reportData)
}

// TdQuoteBodyDescriptor represents the TD quote body descriptor
// Used in Quote v5 to describe the report body type and size
type TdQuoteBodyDescriptor struct {
	TdQuoteBodyType uint16 // TD quote body type (DCAP QVL: TdQuoteBodyType)
	Size            uint32 // Size of the quote body (DCAP QVL: Size)
}

// TdReport15 represents the TD report version 1.5
// Based on Intel DCAP QVL: TD Report 1.5 structure
type TdReport15 struct {
	TeeTcbSvn      [16]byte // TEE TCB SVN (DCAP QVL: teeTcbSvn)
	MrSeam         [48]byte // SEAM measurement (DCAP QVL: mrSeam)
	MrSignerSeam   [48]byte // SEAM signer measurement (DCAP QVL: mrSignerSeam)
	SeamAttributes [8]byte  // SEAM attributes (DCAP QVL: seamAttributes)
	TdAttributes   [8]byte  // TD attributes (DCAP QVL: tdAttributes)
	XFAM           [8]byte  // Extended features available mask (DCAP QVL: xFAM)
	MrTd           [48]byte // TD measurement (DCAP QVL: mrTd)
	MrConfigId     [48]byte // Configuration measurement (DCAP QVL: mrConfigId)
	MrOwner        [48]byte // Owner measurement (DCAP QVL: mrOwner)
	MrOwnerConfig  [48]byte // Owner configuration measurement (DCAP QVL: mrOwnerConfig)
	Rtmr0          [48]byte // Runtime measurement register 0 (DCAP QVL: rtMr0)
	Rtmr1          [48]byte // Runtime measurement register 1 (DCAP QVL: rtMr1)
	Rtmr2          [48]byte // Runtime measurement register 2 (DCAP QVL: rtMr2)
	Rtmr3          [48]byte // Runtime measurement register 3 (DCAP QVL: rtMr3)
	ReportData     [64]byte // Report data (DCAP QVL: reportData)
	TeeTcbSvn2     [16]byte // TEE TCB SVN 2 (DCAP QVL: teeTcbSvn2)
	MrServiceTd    [48]byte // Service TD measurement (DCAP QVL: mrServiceTd)
}

// QeCertificationData represents the QE certification data
type QeCertificationData struct {
	CertificationDataType uint16      // Type of certification data (DCAP QVL: type)
	Size                  uint32      // Size of parsed data (DCAP QVL: parsedDataSize)
	CertificationData     interface{} // Certification data (DCAP QVL: data)
}

type QeReportCertificationData struct {
	QeReport             EnclaveReportBody   // Enclave report (DCAP QVL: enclaveReport)
	QeReportSignature    [64]byte            // Signature (DCAP QVL: signature)
	QeAuthenticationData []byte              // Authentication data (DCAP QVL: authData)
	QeCertificationData  QeCertificationData // Certification data (DCAP QVL: certificationData)
}

// TdxEcdsaQuote represents a parsed TDX ECDSA256 quote with all its components
// TDX quotes (v4/v5) have a nested QE certification data structure:
// - Outer: QeCertificationData with Type 6, data contains QeReportCertificationData bytes
// - Inner: QeReportCertificationData with nested CertificationData (usually Type 5 PCK cert chain)
type TdxEcdsaQuote struct {
	Header              QuoteHeader            // Quote header
	BodyDescriptor      *TdQuoteBodyDescriptor // Quote body descriptor (mandatory for v5)
	Report              interface{}            // TdReport10 or TdReport15 or EnclaveReportBody depending on version
	SignatureDataLen    uint32                 // Signature data length
	QuoteSignature      [64]byte               // ECDSA signature over quote (DCAP QVL: ecdsa256BitSignature)
	EcdsaAttestationKey [64]byte               // ECDSA attestation key (DCAP QVL: ecdsaAttestationKey)
	QeCertificationData QeCertificationData    // QE Certification Data structure (The QeCertificationData.CertificationData field contains the QeReportCertificationData structure)
}

// ------------------------------------------------------------
// TDX quote verification collateral types (ECDSA Cert)
// ------------------------------------------------------------

// EcdsaCertChain represents a parsed certificate chain
type EcdsaCertChain struct {
	// Based on Intel DCAP QVL: AttestationLibrary/src/CertVerification/CertificateChain.h:120-123
	Certificates []*x509.Certificate // All certificates in chain
	RootCA       *x509.Certificate   // Root certificate (self-signed)
	TopMostCert  *x509.Certificate   // Topmost certificate (not used to sign others)
	PCKCert      *x509.Certificate   // PCK certificate (identified by CN)
}

// SGX Extension ASN.1 structure for parsing
type SGXExtensionEntry struct {
	OID   asn1.ObjectIdentifier
	Value asn1.RawValue
}

// PCKCertificateFlags represents configuration flags extracted from PCK certificate
type PCKCertificateFlags struct {
	DynamicPlatform uint8 // 0=undefined, 1=false, 2=true
	CachedKeys      uint8 // 0=undefined, 1=false, 2=true
	SmtEnabled      uint8 // 0=undefined, 1=false, 2=true
}

// Intel OIDs for SGX extensions
// Based on Intel DCAP QVL: AttestationLibrary/src/AttestationParsers/src/X509/PckCertificate.cpp
var (
	OIDSGXExtension = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1} // SGX Extension OID
	// Based on Intel DCAP QVL: AttestationParsers/test/CommonTestUtils/X509CertGenerator.cpp: SGX_PLATFORM_INSTANCE_ID_OID_STR = "1.2.840.113741.1.13.1.6"
	OIDSGXPlatformInstanceID = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 6}
	OIDSGXFmspc              = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 4} // SGX FMSPC OID (6 bytes)
	OIDSGXPceid              = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 3} // SGX PCEID OID (2 bytes)

	// TCB related OIDs - Based on Intel DCAP QVL: AttestationParsers/src/ParserUtils.h
	OIDSGXTcb    = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2}     // TCB Extension OID
	OIDSGXCpuSvn = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 18} // CPU SVN OID (16 bytes)
	OIDSGXPceSvn = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 17} // PCE SVN OID (2 bytes)

	// Configuration related OIDs - Based on Intel DCAP QVL: AttestationParsers/test/CommonTestUtils/X509CertGenerator.cpp
	OIDSGXConfiguration   = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 7}    // Configuration Extension OID
	OIDSGXDynamicPlatform = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 7, 1} // Dynamic Platform OID
	OIDSGXCachedKeys      = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 7, 2} // Cached Keys OID
	OIDSGXSmtEnabled      = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 7, 3} // SMT Enabled OID

	// Individual TCB Component OIDs (16 components)
	OIDSGXTcbComp01 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 1}
	OIDSGXTcbComp02 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 2}
	OIDSGXTcbComp03 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 3}
	OIDSGXTcbComp04 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 4}
	OIDSGXTcbComp05 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 5}
	OIDSGXTcbComp06 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 6}
	OIDSGXTcbComp07 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 7}
	OIDSGXTcbComp08 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 8}
	OIDSGXTcbComp09 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 9}
	OIDSGXTcbComp10 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 10}
	OIDSGXTcbComp11 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 11}
	OIDSGXTcbComp12 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 12}
	OIDSGXTcbComp13 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 13}
	OIDSGXTcbComp14 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 14}
	OIDSGXTcbComp15 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 15}
	OIDSGXTcbComp16 = asn1.ObjectIdentifier{1, 2, 840, 113741, 1, 13, 1, 2, 16}
)

// CollateralDates holds all the date information extracted from collateral components
type CollateralDates struct {
	EarliestIssueDate            int64 // p_earliest_issue_date
	EarliestExpirationDate       int64 // p_earliest_expiration_date
	LatestIssueDate              int64 // p_latest_issue_date
	LatestExpirationDate         int64 // p_latest_expiration_date
	QeIdenEarliestIssueDate      int64 // p_qe_iden_earliest_issue_date
	QeIdenLatestIssueDate        int64 // p_qe_iden_latest_issue_date
	QeIdenEarliestExpirationDate int64 // p_qe_iden_earliest_expiration_date
}

// ------------------------------------------------------------
// TDX quote verification collateral types (Qe Identify)
// ------------------------------------------------------------

// Intel QE Vendor ID
// Based on Intel DCAP QVL: AttestationLibrary/src/Verifiers/QuoteVerifier.cpp
// Intel QE Vendor ID: 939A7233-F79C-4CA9-940A-0DB3957F0607
var (
	INTEL_QE_VENDOR_ID = [16]byte{0x93, 0x9A, 0x72, 0x33, 0xF7, 0x9C, 0x4C, 0xA9,
		0x94, 0x0A, 0x0D, 0xB3, 0x95, 0x7F, 0x06, 0x07}
)

// EnclaveID represents the enclave identity type
// Based on Intel DCAP QVL: AttestationLibrary/src/AttestationParsers/src/Json/EnclaveIdentityV2.cpp
type EnclaveID string

const (
	// EnclaveIDQE represents SGX Quoting Enclave
	EnclaveIDQE EnclaveID = "QE"
	// EnclaveIDTDQE represents TDX Quoting Enclave
	EnclaveIDTDQE EnclaveID = "TD_QE"
)

// QEIdentityTcbComponent represents QE Identity TCB component levels
type QeIdentityTcbComponent struct {
	IsvSvn int `json:"isvsvn"`
}

// QeIdentityTcbLevel represents QE Identity TCB Level information
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationLibrary/src/Verifiers/EnclaveIdentityV2.h
type QeIdentityTcbLevel struct {
	Tcb         QeIdentityTcbComponent `json:"tcb"`
	TcbDate     string                 `json:"tcbDate"`
	TcbStatus   string                 `json:"tcbStatus"`
	AdvisoryIDs []string               `json:"advisoryIDs,omitempty"` // Advisory IDs for vulnerabilities (present in TDX QE Identity)
}

// QEIdentity represents QE Identity information
// Based on Intel DCAP QVL: AttestationLibrary/src/AttestationParsers/src/Json/EnclaveIdentityV2.cpp
type QeIdentity struct {
	ID                      EnclaveID            `json:"id"`
	Version                 int                  `json:"version"`
	IssueDate               string               `json:"issueDate"`
	NextUpdate              string               `json:"nextUpdate"`
	TcbEvaluationDataNumber int                  `json:"tcbEvaluationDataNumber"`
	MiscSelect              string               `json:"miscselect"`
	MiscSelectMask          string               `json:"miscselectMask"`
	Attributes              string               `json:"attributes"`
	AttributesMask          string               `json:"attributesMask"`
	MrSigner                string               `json:"mrsigner"`
	IsvProdId               int                  `json:"isvprodid"`
	TcbLevels               []QeIdentityTcbLevel `json:"tcbLevels"`
}

// QEIdentityResponse represents the wrapper response from DCAP service
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationParsers/src/Json/EnclaveIdentityV2.cpp:36-45
type QeIdentityResponse struct {
	EnclaveIdentity QeIdentity `json:"enclaveIdentity"`
	Signature       string     `json:"signature"`
}

// QeIdentityWithSignature represents the wrapper response from DCAP service with raw qe identify TcbInfo
// signature verify needed
type QeIdentityWithSignature struct {
	EnclaveIdentity json.RawMessage `json:"enclaveIdentity"`
	Signature       string          `json:"signature"`
}

// ------------------------------------------------------------
// TCB Status map
// ------------------------------------------------------------

var TCB_STATUS_MAP = map[string]Status{
	"UpToDate":                          STATUS_OK,
	"Revoked":                           STATUS_TCB_REVOKED,
	"ConfigurationNeeded":               STATUS_TCB_CONFIGURATION_NEEDED,
	"OutOfDate":                         STATUS_TCB_OUT_OF_DATE,
	"OutOfDateConfigurationNeeded":      STATUS_TCB_OUT_OF_DATE_CONFIGURATION_NEEDED,
	"SWHardeningNeeded":                 STATUS_TCB_SW_HARDENING_NEEDED,
	"ConfigurationAndSWHardeningNeeded": STATUS_TCB_CONFIGURATION_AND_SW_HARDENING_NEEDED,
}

// Valid TCB status sets as per Intel DCAP QVL: TcbStatus.h:80-85
var (
	// ValidTCBInfoStatuses contains all valid TCB Info status strings
	ValidTCBInfoStatuses = map[string]bool{
		"UpToDate":                          true,
		"OutOfDate":                         true,
		"ConfigurationNeeded":               true,
		"Revoked":                           true,
		"OutOfDateConfigurationNeeded":      true,
		"SWHardeningNeeded":                 true,
		"ConfigurationAndSWHardeningNeeded": true,
	}

	// ValidModuleTCBStatuses contains valid module TCB status strings
	ValidModuleTCBStatuses = map[string]bool{
		"UpToDate":  true,
		"OutOfDate": true,
		"Revoked":   true,
	}
)

// ------------------------------------------------------------
// TDX quote verification collateral types (Tcb Info)
// ------------------------------------------------------------

// TdxModule represents TDX Module information in TCB Info
type TdxModule struct {
	MrSigner       string `json:"mrsigner"`
	Attributes     string `json:"attributes"`
	AttributesMask string `json:"attributesMask"`
}

// TdxModuleTcb represents TDX Module TCB information
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationParsers/include/SgxEcdsaAttestation/AttestationParsers.h:144-158
type TdxModuleTcb struct {
	IsvSvn int `json:"isvsvn"` // TDX Module's ISV SVN (uint16_t _isvsvn)
}

// TdxModuleTcbLevel represents TDX Module TCB Level information
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationParsers/include/SgxEcdsaAttestation/AttestationParsers.h:163-184
type TdxModuleTcbLevel struct {
	Tcb         TdxModuleTcb `json:"tcb"`                   // TDX Module TCB information (TdxModuleTcb _tcb)
	TcbDate     string       `json:"tcbDate"`               // ISO 8601 date format (std::time_t _tcbDate)
	TcbStatus   string       `json:"tcbStatus"`             // TCB level status (std::string _tcbStatus)
	AdvisoryIDs []string     `json:"advisoryIDs,omitempty"` // Advisory IDs for vulnerabilities (std::vector<std::string> _advisoryIDs)
}

// TdxModuleIdentity represents TDX Module Identity information
// Based on Intel DCAP QVL: AttestationLibrary/src/AttestationParsers/include/SgxEcdsaAttestation/AttestationParsers.h:191-232
type TdxModuleIdentity struct {
	ID             string              `json:"id"`             // TDX Module Identity ID (e.g., "TDX_00")
	MrSigner       string              `json:"mrsigner"`       // 48 bytes hex-encoded MRSIGNER (SHA384 hash)
	Attributes     string              `json:"attributes"`     // 8 bytes hex-encoded attributes
	AttributesMask string              `json:"attributesMask"` // 8 bytes hex-encoded attributes mask
	TcbLevels      []TdxModuleTcbLevel `json:"tcbLevels"`      // Sorted list of supported TCB levels
}

// TcbComponentSvn represents a TCB component with SVN value (used by both SGX and TDX)
type TcbComponentSvn struct {
	Svn      int    `json:"svn"`
	Category string `json:"category"`
	Type     string `json:"type"`
}

// Type aliases for backward compatibility and clarity
type SgxTcbComponent = TcbComponentSvn
type TdxTcbComponent = TcbComponentSvn

// TcbComponent represents TCB component levels
type TcbComponent struct {
	SgxTcbComponents []SgxTcbComponent `json:"sgxtcbcomponents,omitempty"`
	TdxTcbComponents []TdxTcbComponent `json:"tdxtcbcomponents,omitempty"`
	PceSvn           int               `json:"pcesvn"`
}

// TcbLevel represents a TCB level in TCB info (renamed to match DCAP QVL)
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationParsers/include/SgxEcdsaAttestation/AttestationParsers.h:380-549
type TcbLevel struct {
	Tcb         TcbComponent `json:"tcb"`
	TcbDate     string       `json:"tcbDate"`
	TcbStatus   string       `json:"tcbStatus"`
	AdvisoryIDs []string     `json:"advisoryIDs,omitempty"` // Advisory IDs for vulnerabilities (std::vector<std::string> _advisoryIDs)
}

// TCBInfo represents TCB information from DCAP service
type TcbInfo struct {
	ID                      string              `json:"id"`
	Version                 int                 `json:"version"`
	IssueDate               string              `json:"issueDate"`
	NextUpdate              string              `json:"nextUpdate"`
	Fmspc                   string              `json:"fmspc"`
	PceId                   string              `json:"pceId"`
	TcbType                 int                 `json:"tcbType"`
	TcbEvaluationDataNumber int                 `json:"tcbEvaluationDataNumber"`
	TdxModule               TdxModule           `json:"tdxModule,omitempty"`
	TdxModuleIdentities     []TdxModuleIdentity `json:"tdxModuleIdentities,omitempty"`
	TcbLevels               []TcbLevel          `json:"tcbLevels"`
}

// TCBInfoResponse represents the wrapper response from DCAP service
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationParsers/src/Json/TcbInfo.cpp:36-45
type TcbInfoResponse struct {
	TcbInfo   TcbInfo `json:"tcbInfo"`
	Signature string  `json:"signature"`
}

// TcbInfoWithSignature represents the wrapper response from DCAP service with raw json TcbInfo
// signature verify needed
type TcbInfoWithSignature struct {
	TcbInfo   json.RawMessage `json:"tcbInfo"`
	Signature string          `json:"signature"`
}

// ------------------------------------------------------------
// TDX quote verification supplemental data types
// ------------------------------------------------------------

// SupplementalData represents supplemental data structure for quote verification
// Based on Intel DCAP QVL: QuoteVerification/QVL/Src/AttestationLibrary/include/QuoteVerification/Quote.h:85-110
type SupplementalData struct {
	Version                  uint32    // Version 3.3 format: 0x00030003 (Intel DCAP QVL standard)
	EarliestIssueDate        time.Time // Earliest issue date from collateral
	LatestIssueDate          time.Time // Latest issue date from collateral
	EarliestExpirationDate   time.Time // Earliest expiration date from collateral
	TcbLevelDateTag          time.Time // TCB level date tag
	PckCrlNum                uint32    // PCK CRL sequence number
	RootCaCrlNum             uint32    // Root CA CRL sequence number
	TcbEvalRefNum            uint32    // TCB evaluation reference number
	RootKeyId                [48]byte  // Root Key ID
	PckPpid                  [16]byte  // PCK PPID (Platform Provisioning ID)
	TcbCpusvn                [16]byte  // TCB CPU SVN
	TcbPceIsvsvn             uint16    // TCB PCE ISV SVN
	PceId                    uint16    // PCE ID
	TeeType                  uint32    // TEE type (SGX/TDX)
	SgxType                  uint8     // SGX type
	PlatformInstanceId       [16]byte  // Platform instance ID
	DynamicPlatform          uint8     // Dynamic platform flag
	CachedKeys               uint8     // Cached keys flag
	SmtEnabled               uint8     // SMT enabled flag
	SecurityAdvisories       string    // Security advisories list (320 bytes)
	QeIdentEarliestIssueDate time.Time // QE Identity earliest issue date
	QeIdentLatestIssueDate   time.Time // QE Identity latest issue date
	QeIdentEarliestExpDate   time.Time // QE Identity earliest expiration date
	QeIdentTcbLevelDateTag   time.Time // QE Identity TCB level date tag
	QeIdentTcbEvalRefNum     uint32    // QE Identity TCB evaluation reference number
	QeIdentStatus            Status    // QE Identity verification status
}

// PckTcb represents PCK certificate TCB values
type PckTcb struct {
	CpuSvn []byte // CPU SVN (16 bytes)
	PceSvn uint16 // PCE SVN
	Fmspc  []byte // FMSPC (6 bytes)
}

// ------------------------------------------------------------
// Collateral and Provider types
// ------------------------------------------------------------

// Collateral represents the complete collateral structure needed for quote verification
// Based on Intel DCAP QVL: sgx_ql_qve_collateral_t
type Collateral struct {
	Version               uint32    // Collateral version
	TeeType               uint32    // TEE type (SGX/TDX)
	PckCrlIssuerChain     []byte    // PCK CRL issuer certificate chain
	RootCaCrl             []byte    // Root CA CRL
	PckCrl                []byte    // PCK CRL
	TcbInfoIssuerChain    []byte    // TCB Info issuer certificate chain
	TcbInfo               []byte    // TCB Info JSON data
	QeIdentityIssuerChain []byte    // QE Identity issuer certificate chain
	QeIdentity            []byte    // QE Identity JSON data
	RetrievedAt           time.Time // Timestamp when collateral was retrieved
}

// ------------------------------------------------------------
// TDX event log types
// ------------------------------------------------------------

// SHA384 digest constants for special cases
var (
	SHA384_DIGEST_ONE  = []byte{141, 44, 232, 125, 134, 245, 95, 207, 171, 119, 10, 4, 123, 9, 13, 162, 50, 112, 250, 32, 104, 50, 223, 234, 126, 12, 148, 111, 255, 69, 31, 129, 154, 221, 36, 35, 116, 190, 85, 27, 13, 99, 24, 237, 108, 125, 65, 216}
	SHA384_DIGEST_ZERO = []byte{190, 192, 33, 180, 243, 104, 227, 6, 145, 52, 224, 18, 194, 180, 48, 112, 131, 211, 169, 189, 210, 6, 226, 78, 95, 13, 134, 225, 61, 102, 54, 101, 89, 51, 236, 43, 65, 52, 101, 150, 104, 23, 169, 194, 8, 161, 23, 23}
)

// IPL keyword constants for event log parsing
var (
	IPL_KEYWORD_MOK_LIST_TRUSTED_BYES = []byte{'M', 'o', 'k', 'L', 'i', 's', 't', 'T', 'r', 'u', 's', 't', 'e', 'd', 0}
	IPL_KEYWORD_KERNEL_CMDLINE        = []byte{'k', 'e', 'r', 'n', 'e', 'l', '_', 'c', 'm', 'd', 'l', 'i', 'n', 'e'}
	IPL_KEYWORD_MODULE_CMDLINE        = []byte{'m', 'o', 'd', 'u', 'l', 'e', '_', 'c', 'm', 'd', 'l', 'i', 'n', 'e'}
	IPL_KEYWORD_GRUB_CMDLINE          = []byte{'g', 'r', 'u', 'b', '_', 'c', 'm', 'd'}
	IPL_KEYWORD_GRUB_LINUXEFI         = []byte{'g', 'r', 'u', 'b', '_', 'l', 'i', 'n', 'u', 'x', 'e', 'f', 'i'}
	IPL_KEYWORD_GRUB_KERNEL_CMDLINE   = []byte{'g', 'r', 'u', 'b', '_', 'k', 'e', 'r', 'n', 'e', 'l', '_', 'c', 'm', 'd', 'l', 'i', 'n', 'e'}
	IPL_KEYWORD_MOK_LIST              = []byte{'M', 'o', 'k', 'L', 'i', 's', 't', 0}
	IPL_KEYWORD_MOK_LISTX             = []byte{'M', 'o', 'k', 'L', 'i', 's', 't', 'X', 0}
)

// TDAlgorithm represents an algorithm entry in the event log header
type TDAlgorithm struct {
	AlgorithmId uint16
	DigestSize  uint16
}

// TDEventLogSpecIdHeader represents the header of a TD event log
type TDEventLogSpecIdHeader struct {
	TDRegisterIndex        uint32
	EventType              uint32
	DigestCount            uint32
	ZeroDigest             [20]byte
	NoIdea                 [24]byte
	AlgorithmNumber        uint32
	AlgorithmId2DigestSize map[uint16]uint16
	VendorSize             uint8
	RawData                []byte
}

// TDEventLogEntry represents a single entry in the TD event log
type TDEventLogEntry struct {
	TDRegisterIndex uint32
	EventType       uint32
	DigestCount     uint32
	AlgorithmId     uint16
	Digests         [][]byte
	EventSize       uint32
	Event           []byte
	RawData         []byte
}

// TDEventLog represents a complete TD event log
type TDEventLog struct {
	Entries []*TDEventLogEntry
	Header  *TDEventLogSpecIdHeader
}

// VariableLog represents a UEFI variable log entry
type VariableLog struct {
	VariableName       [16]byte // UUID as raw bytes
	UnicodeNameLength  uint64
	VariableDataLength uint64
	UnicodeName        []uint16
	VariableData       []byte
}

// AAELContainerEvent represents a container image measurement from an AAEL event.
// Either Name (legacy) or Reference (PAI) will be populated
// depending on the source operation;
// Digest is always present after a successful parse.
type AAELContainerEvent struct {
	Name      string `json:"name,omitempty"`      // legacy form, e.g. "cvm_container_proxy"
	Reference string `json:"reference,omitempty"` // PAI form, OCI image reference
	Digest    string `json:"digest"`              // e.g. "sha256:abc123..."
}
