package traces

import (
	
	
	
)

// Span represents an in-flight span created by [Tracer.Start].
//
// All methods are safe for concurrent use. On a non-recording span, mutation
// methods and [Span.End] are no-ops.
type Span struct {
	tracer *Tracer
	ref    SpanRef
	state  *spanState
}

// Ref returns the span’s immutable [SpanRef] for use as a parent or for
// propagation across process boundaries.
func ( *Span) () SpanRef {
	return .ref
}

// IsRecording reports whether span data is being recorded.
func ( *Span) () bool {
	return .state != nil
}

// SetName updates the span’s name (for example once an HTTP route pattern is
// known). It has no effect after [Span.End].
func ( *Span) ( string) {
	if .state != nil {
		.state.setName()
	}
}

// SetStart overrides the span’s start timestamp. It has no effect after
// [Span.End].
func ( *Span) ( time.Time) {
	if .state != nil {
		.state.setStart()
	}
}

// SetAttrs sets attributes on the span, replacing any existing attribute with
// the same key. It has no effect after [Span.End].
func ( *Span) ( ...Attr) {
	if .state != nil {
		.state.setAttrs(...)
	}
}

// SetError records an error on the span. A nil error is ignored. It has no
// effect after [Span.End].
func ( *Span) ( error) {
	if .state != nil &&  != nil {
		.state.setError()
	}
}

// End finishes the span and passes its [Record] to the tracer’s [Handler] with
// ctx. Subsequent calls to End are no-ops.
func ( *Span) ( context.Context) {
	if .state == nil {
		return
	}
	if ,  := .state.finish(.tracer.now());  {
		_ = .tracer.handler.Handle(, )
	}
}

// EndError is a defer helper that calls [Span.SetError] when errp points to a
// non-nil error, and then calls [Span.End]:
//
//	func doWork(ctx context.Context, tr *traces.Tracer) (err error) {
//		sp := tr.Start(ctx, traces.FromContext(ctx), "doWork")
//		defer traces.EndError(ctx, sp, &err)
//		...
//	}
func ( context.Context,  *Span,  *error) {
	if  != nil && * != nil {
		.SetError(*)
	}
	.End()
}

type spanState struct {
	mu    sync.Mutex
	rec   Record
	ended bool
}

func ( Record) *spanState {
	 := .Attrs
	.Attrs = nil
	 := &spanState{rec: }
	.setAttrs(...)
	return 
}

func ( *spanState) ( string) {
	.mu.Lock()
	defer .mu.Unlock()
	if !.ended {
		.rec.Name = 
	}
}

func ( *spanState) ( time.Time) {
	.mu.Lock()
	defer .mu.Unlock()
	if !.ended {
		.rec.Start = 
	}
}

func ( *spanState) ( ...Attr) {
	.mu.Lock()
	defer .mu.Unlock()
	if .ended {
		return
	}
:
	for ,  := range  {
		for  := range .rec.Attrs {
			if .rec.Attrs[].Key == .Key {
				.rec.Attrs[] = 
				continue 
			}
		}
		.rec.Attrs = append(.rec.Attrs, )
	}
}

func ( *spanState) ( error) {
	.mu.Lock()
	defer .mu.Unlock()
	if !.ended {
		.rec.Err = 
	}
}

func ( *spanState) ( time.Time) (Record, bool) {
	.mu.Lock()
	defer .mu.Unlock()
	if .ended {
		return Record{}, false
	}
	.ended = true
	.rec.End = 
	return .rec, true
}