// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package log

import (
	
	
	
	

	
	
	
	
	
	
	
	
	
)

const (
	defaultAttrCntLim      = 128
	defaultAttrValLenLim   = -1
	defaultAttrValDepthLim = 64

	envarAttrCntLim    = "OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT"
	envarAttrValLenLim = "OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT"
)

type providerConfig struct {
	resource        *resource.Resource
	processors      []Processor
	attrCntLim      setting[int]
	attrValLenLim   setting[int]
	attrValDepthLim setting[int]
	allowDupKeys    setting[bool]
}

type experimentalOption interface {
	Experimental()
}

func newProviderConfig( []LoggerProviderOption) providerConfig {
	var  providerConfig
	for ,  := range  {
		if ,  := .(experimentalOption);  {
			continue
		}
		 = .apply()
	}

	if .resource == nil {
		.resource = resource.Default()
	}

	.attrCntLim = .attrCntLim.Resolve(
		getenv[int](envarAttrCntLim),
		fallback[int](defaultAttrCntLim),
	)

	.attrValLenLim = .attrValLenLim.Resolve(
		getenv[int](envarAttrValLenLim),
		fallback[int](defaultAttrValLenLim),
	)

	.attrValDepthLim = .attrValDepthLim.Resolve(
		fallback[int](defaultAttrValDepthLim),
	)

	return 
}

// LoggerProvider handles the creation and coordination of Loggers. All Loggers
// it creates are associated with the same Resource.
//
// After [LoggerProvider.Shutdown] starts, calls to [log.Logger.Enabled] on
// Loggers created by the LoggerProvider return false, and calls to
// [log.Logger.Emit] perform no operation.
type LoggerProvider struct {
	embedded.LoggerProvider

	resource                  *resource.Resource
	processors                []Processor
	attributeCountLimit       int
	attributeValueLengthLimit int
	attributeValueDepthLimit  int
	allowDupKeys              bool

	loggersMu sync.Mutex
	loggers   map[instrumentation.Scope]*logger

	stopped                   atomic.Bool
	processorOperationsMu     sync.Mutex
	processorOperationsActive int
	processorOperationsDone   chan struct{}

	noCmp [0]func() //nolint: unused  // This is indeed used.
}

// This is a compile-time check that LoggerProvider implements
// log.LoggerProvider.
var _ log.LoggerProvider = (*LoggerProvider)(nil)

// NewLoggerProvider returns a new, configured LoggerProvider.
//
// By default, the returned LoggerProvider is configured with the default
// Resource and no Processors. Processors cannot be added after a LoggerProvider
// is created. This means the returned LoggerProvider, one created with no
// Processors, will perform no operations.
func ( ...LoggerProviderOption) *LoggerProvider {
	 := newProviderConfig()
	return &LoggerProvider{
		resource:                  .resource,
		processors:                .processors,
		attributeCountLimit:       .attrCntLim.Value,
		attributeValueLengthLimit: .attrValLenLim.Value,
		attributeValueDepthLimit:  .attrValDepthLim.Value,
		allowDupKeys:              .allowDupKeys.Value,
	}
}

// Logger returns a new [log.Logger] with the provided name and configuration.
//
// Calls made after [LoggerProvider.Shutdown] starts return a [noop.Logger].
//
// Instrumentation scope attributes with invalid keys are ignored.
//
// This method can be called concurrently.
func ( *LoggerProvider) ( string,  ...log.LoggerOption) log.Logger {
	if  == "" {
		global.Warn("Invalid Logger name.", "name", )
	}

	if .stopped.Load() {
		return noop.NewLoggerProvider().Logger(, ...)
	}

	 := log.NewLoggerConfig(...)
	 := .InstrumentationAttributes()
	,  := .Filter(attribute.KeyValue.Valid)
	if len() > 0 {
		logInvalidAttribute()
	}
	if !.allowDupKeys {
		, _, _ = attrnorm.SetDedupLimitDepth(, .attrValueDepthLimit())
	} else {
		, _ = attrnorm.SetLimitDepth(, .attrValueDepthLimit())
	}
	 := instrumentation.Scope{
		Name:       ,
		Version:    .InstrumentationVersion(),
		SchemaURL:  .SchemaURL(),
		Attributes: ,
	}

	.loggersMu.Lock()
	defer .loggersMu.Unlock()

	if .loggers == nil {
		 := newLogger(, )
		.loggers = map[instrumentation.Scope]*logger{: }
		return 
	}

	,  := .loggers[]
	if ! {
		 = newLogger(, )
		.loggers[] = 
	}

	return 
}

func ( *LoggerProvider) () int {
	if .attributeValueDepthLimit == 0 {
		return defaultAttrValDepthLim
	}
	return .attributeValueDepthLimit
}

// Shutdown shuts down the provider and all processors in the order they were
// registered.
//
// The first call stops admitting new operations that invoke a processor's
// Enabled, OnEmit, or ForceFlush method. It waits for operations already
// admitted to complete before synchronously invoking each processor's Shutdown
// method. If ctx is canceled before the admitted operations complete, Shutdown
// returns ctx.Err() without invoking any processor's Shutdown method.
//
// Concurrent or subsequent Shutdown calls return nil without invoking any
// processor's Shutdown method.
//
// Shutdown must not be called directly or indirectly from a Processor method.
//
// This method can be called concurrently.
func ( *LoggerProvider) ( context.Context) error {
	.processorOperationsMu.Lock()
	if .stopped.Load() {
		.processorOperationsMu.Unlock()
		return nil
	}
	.processorOperationsDone = make(chan struct{})
	.stopped.Store(true)
	if .processorOperationsActive == 0 {
		close(.processorOperationsDone)
	}
	.processorOperationsMu.Unlock()

	// All count updates happen while processorOperationsMu is held. Therefore,
	// either Shutdown observes zero operations and closes the channel above, or
	// the final operation observes stopped and closes it synchronously.
	if  := .waitForProcessorOperations();  != nil {
		return 
	}

	var  error
	for ,  := range .processors {
		 = errors.Join(, .Shutdown())
	}
	return 
}

// ForceFlush flushes all processors.
//
// Once Shutdown starts, ForceFlush performs no operation and returns nil.
//
// This method can be called concurrently.
func ( *LoggerProvider) ( context.Context) error {
	if len(.processors) == 0 || !.beginProcessorOperation() {
		return nil
	}
	defer .endProcessorOperation()

	var  error
	for ,  := range .processors {
		 = errors.Join(, .ForceFlush())
	}
	return 
}

func ( *LoggerProvider) () bool {
	.processorOperationsMu.Lock()
	defer .processorOperationsMu.Unlock()
	if .stopped.Load() {
		return false
	}
	.processorOperationsActive++
	return true
}

func ( *LoggerProvider) () {
	.processorOperationsMu.Lock()
	defer .processorOperationsMu.Unlock()
	.processorOperationsActive--
	if .processorOperationsActive == 0 && .stopped.Load() {
		close(.processorOperationsDone)
	}
}

func ( *LoggerProvider) ( context.Context) error {
	if  := .Err();  != nil {
		return 
	}

	return waitForProcessorOperationsCompletion(, .processorOperationsDone)
}

func waitForProcessorOperationsCompletion( context.Context,  <-chan struct{}) error {
	select {
	case <-:
	case <-.Done():
		// Prefer a completed drain when it races with cancellation.
		select {
		case <-:
		default:
			return .Err()
		}
	}
	return nil
}

// LoggerProviderOption applies a configuration option value to a LoggerProvider.
type LoggerProviderOption interface {
	apply(providerConfig) providerConfig
}

type loggerProviderOptionFunc func(providerConfig) providerConfig

func ( loggerProviderOptionFunc) ( providerConfig) providerConfig {
	return ()
}

// WithResource associates a Resource with a LoggerProvider. This Resource
// represents the entity producing telemetry and is associated with all Loggers
// the LoggerProvider will create.
//
// By default, if this Option is not used, the default Resource from the
// go.opentelemetry.io/otel/sdk/resource package will be used.
func ( *resource.Resource) LoggerProviderOption {
	return loggerProviderOptionFunc(func( providerConfig) providerConfig {
		var  error
		.resource,  = resource.Merge(resource.Environment(), )
		if  != nil {
			otel.Handle()
		}
		return 
	})
}

// WithProcessor associates a Processor with a LoggerProvider.
//
// By default, if this option is not used, the LoggerProvider will perform no
// operations; no data will be exported without a processor.
//
// The SDK invokes the processors sequentially in the same order as they were
// registered.
//
// For production, use [NewBatchProcessor] to batch log records before they are
// exported. For testing and debugging, use [NewSimpleProcessor] to
// synchronously export log records.
func ( Processor) LoggerProviderOption {
	return loggerProviderOptionFunc(func( providerConfig) providerConfig {
		.processors = append(.processors, )
		return 
	})
}

// WithAttributeCountLimit sets the maximum allowed log record attribute count.
// Any attribute added to a log record once this limit is reached will be dropped.
//
// Setting this to zero means no attributes will be recorded.
//
// Setting this to a negative value means no limit is applied.
//
// If the OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT environment variable is set and
// this option is not passed, the value of that variable will be used.
//
// By default, if the environment variable is not set and this option is not
// passed, 128 will be used.
func ( int) LoggerProviderOption {
	return loggerProviderOptionFunc(func( providerConfig) providerConfig {
		.attrCntLim = newSetting()
		return 
	})
}

// WithAttributeValueLengthLimit sets the maximum allowed attribute value length.
//
// This limit only applies to string, string slice, and byte slice attribute values.
// Strings and byte slices longer than this value will be truncated to this length.
//
// Setting this to a negative value means no limit is applied.
//
// If the OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT environment variable is
// set and this option is not passed, the value of that variable will be used.
//
// By default, if the environment variable is not set and this option is not
// passed, no limit (-1) will be used.
func ( int) LoggerProviderOption {
	return loggerProviderOptionFunc(func( providerConfig) providerConfig {
		.attrValLenLim = newSetting()
		return 
	})
}

// WithAttributeValueDepthLimit sets the maximum allowed depth for attribute
// values. Depth starts at one for the top-level value and increments when
// descending into an array element or map value. An array or map beyond this
// depth is replaced by an empty value.
//
// This limit applies to log record and instrumentation scope attributes
// processed by this LoggerProvider. It does not apply to Resource attributes
// or log record bodies.
//
// Setting this to zero means the default limit of 64 is used. Setting this to
// a negative value means no limit is applied.
//
// There is no environment variable for this limit.
func ( int) LoggerProviderOption {
	if  == 0 {
		 = defaultAttrValDepthLim
	}
	return loggerProviderOptionFunc(func( providerConfig) providerConfig {
		.attrValDepthLim = newSetting()
		return 
	})
}

// WithAllowKeyDuplication sets whether deduplication is skipped for log record
// and instrumentation scope key-value collections.
//
// By default, the key-value collections within a log record and an
// instrumentation scope are deduplicated to comply with the OpenTelemetry
// Specification.
// Deduplication means that if multiple key-value pairs with the same key are
// present, only a single pair is retained and the others are discarded.
// Resource attributes are always deduplicated by
// go.opentelemetry.io/otel/sdk/resource.
//
// Disabling deduplication with this option can improve performance when adding
// attributes to the log record.
//
// Receivers may handle duplicate keys unpredictably. If you disable
// deduplication, you are responsible for ensuring that duplicate keys within a
// single collection are not emitted, or that the telemetry receiver can handle
// such duplicates.
func () LoggerProviderOption {
	return loggerProviderOptionFunc(func( providerConfig) providerConfig {
		.allowDupKeys = newSetting(true)
		return 
	})
}