package batchtraces

import (
	
	
	
	
	

	

	
)

var errAlreadyRunning = errors.New("batchtraces: already running")

// Stats is a point-in-time snapshot of [Batcher] counters.
type Stats struct {
	// Exported is the number of spans successfully exported.
	Exported uint64
	// Dropped is the number of spans dropped because all export slots were
	// busy or because the batcher was not running.
	Dropped uint64
	// Failed is the number of spans whose Export call returned an error.
	Failed uint64
}

var _ traces.Handler = (*Batcher)(nil)

// Batcher buffers finished spans in memory and periodically flushes them in
// batches to an [Exporter].
//
// Batcher starts no goroutines in [NewBatcher]. Call [Batcher.Run] to run the
// flush loop; spans recorded while the batcher is not running are dropped and
// counted in [Stats.Dropped].
type Batcher struct {
	exp     Exporter
	clock   *clock.Clock
	onError func(context.Context, error)

	flushInterval time.Duration
	maxBatch      int
	maxExports    int

	state atomic.Pointer[runState]

	exported atomic.Uint64
	dropped  atomic.Uint64
	failed   atomic.Uint64
}

type runState struct {
	recsc chan traces.Record
	stopc chan struct{}
}

// NewBatcher returns a new [Batcher] instance.
func ( Exporter,  Options) *Batcher {
	.setDefaults()
	return &Batcher{
		exp:           ,
		clock:         .Clock,
		onError:       .OnError,
		flushInterval: .FlushInterval,
		maxBatch:      .MaxBatch,
		maxExports:    .MaxExports,
	}
}

// Handle implements the [traces.Handler] interface. It enqueues rec for
// batched export, or drops it if the batcher is not running.
func ( *Batcher) ( context.Context,  traces.Record) error {
	 := .state.Load()
	if  == nil {
		.dropped.Add(1)
		return nil
	}
	// Intentionally select on s.stopc rather than ctx.Done(): finished spans
	// from canceled or timed-out operations still need to be recorded, and the
	// event loop only performs in-memory appends before receiving again.
	select {
	case <-.stopc:
		.dropped.Add(1)
	case .recsc <- :
	}
	return nil
}

// Run implements the [go.pact.im/x/process.Runner] interface. It starts the
// flush loop, invokes callback, and flushes remaining spans after callback
// returns.
func ( *Batcher) (
	 context.Context,
	 func( context.Context) error,
) error {
	 := &runState{
		recsc: make(chan traces.Record),
		stopc: make(chan struct{}),
	}
	if !.state.CompareAndSwap(nil, ) {
		return errAlreadyRunning
	}
	var  sync.WaitGroup
	.Go(func() {
		.eventLoop(, )
	})
	defer func() {
		.state.Store(nil)
		close(.stopc)
		.Wait()
	}()
	return ()
}

func ( *Batcher) ( context.Context,  *runState) {
	 := .clock.Timer(.flushInterval)
	defer .Stop()

	var  sync.WaitGroup
	defer .Wait()

	 := make(chan struct{}, .maxExports)
	 := make([]traces.Record, 0, .maxBatch)

	 := func() {
		if len() == 0 {
			return
		}
		select {
		case  <- struct{}{}:
		default:
			.dropped.Add(uint64(len()))
			clear()
			 = [:0]
			return
		}
		 := 
		 = make([]traces.Record, 0, .maxBatch)
		.Go(func() {
			defer func() { <- }()
			.export(, )
		})
	}

	for {
		select {
		case <-.stopc:
			if len() > 0 {
				.export(, )
			}
			return
		case  := <-.recsc:
			 = append(, )
			if len() >= .maxBatch {
				()
			}
		case <-.C():
			()
			.Reset(.flushInterval)
		}
	}
}

func ( *Batcher) ( context.Context,  []traces.Record) {
	if  := .exp.Export(, );  != nil {
		.failed.Add(uint64(len()))
		if .onError != nil {
			.onError(, )
		}
		return
	}
	.exported.Add(uint64(len()))
}

// Stats returns a snapshot of the batcher’s counters.
func ( *Batcher) () Stats {
	return Stats{
		Exported: .exported.Load(),
		Dropped:  .dropped.Load(),
		Failed:   .failed.Load(),
	}
}