package httptraces

import (
	
	
	
	
	
	

	
)

// Transport is an [http.RoundTripper] that traces outgoing HTTP requests.
//
// By default, trace context headers are not injected so internal trace IDs are
// not leaked to third-party endpoints; call [Transport.WithInject] to opt in
// for internal or trusted downstream services.
//
// Client spans end when the response body reaches EOF or is closed, or at
// response headers for nil/empty bodies, HEAD requests, errors, and 101
// Switching Protocols responses.
type Transport struct {
	tracer   *traces.Tracer
	base     http.RoundTripper
	filter   func(*http.Request) bool
	inject   func(ref traces.SpanRef, set func(key, value string))
	spanName func(*http.Request) string
	attrs    func(*http.Request) []traces.Attr
}

var _ http.RoundTripper = (*Transport)(nil)

// NewTransport returns a new [Transport] instance wrapping base using tr.
// If base is nil, [http.DefaultTransport] is used.
func ( *traces.Tracer,  http.RoundTripper) *Transport {
	if  == nil {
		 = http.DefaultTransport
	}
	return &Transport{
		tracer:   .WithScope(scopeName),
		base:     ,
		spanName: defaultClientSpanName,
	}
}

// WithFilter returns a [Transport] that only traces requests for which f
// returns true. Filtered-out requests are passed directly to the wrapped
// transport without creating a span or injecting trace headers. If f is nil,
// all requests are traced.
func ( *Transport) ( func(*http.Request) bool) *Transport {
	 := *
	.filter = 
	return &
}

// WithInject returns a [Transport] using f to inject [traces.SpanRef] into
// outgoing request headers (for example [traceparent.Inject]). If f is nil, no
// trace headers are injected.
func ( *Transport) (
	 func( traces.SpanRef,  func(,  string)),
) *Transport {
	 := *
	.inject = 
	return &
}

// WithSpanName returns a [Transport] using f to compute the span name for each
// outgoing request. If f is nil, it restores using the HTTP request method.
func ( *Transport) ( func(*http.Request) string) *Transport {
	if  == nil {
		 = defaultClientSpanName
	}
	 := *
	.spanName = 
	return &
}

// WithAttrs returns a [Transport] using f to attach additional start-time
// attributes for each outgoing request. If f is nil, only default attributes
// are added.
func ( *Transport) ( func(*http.Request) []traces.Attr) *Transport {
	 := *
	.attrs = 
	return &
}

// RoundTrip implements the [http.RoundTripper] interface.
func ( *Transport) ( *http.Request) (*http.Response, error) {
	if .filter != nil && !.filter() {
		return .base.RoundTrip()
	}

	 := .Context()
	 := .spanName()
	if  == "" {
		 = .Method
	}

	 := []traces.Attr{
		traces.String(attrHTTPRequestMethod, .Method),
		traces.String(attrURLFull, .URL.Redacted()),
	}
	if ,  := splitHostPort(.URL.Host);  != "" {
		 = append(, traces.String(attrServerAddress, ))
		if  > 0 {
			 = append(, traces.Int(attrServerPort, ))
		}
	}
	if .attrs != nil {
		 = append(, .attrs()...)
	}

	 := .tracer.Start(, traces.FromContext(), traces.SpanKindClient, , ...)

	if .inject != nil {
		 = .Clone()
		.inject(.Ref(), .Header.Set)
	}

	,  := .base.RoundTrip()
	if  != nil {
		.SetAttrs(traces.String(attrErrorType, fmt.Sprintf("%T", )))
		.SetError()
		.End()
		return nil, 
	}

	.SetAttrs(traces.Int(attrHTTPResponseStatusCode, .StatusCode))
	if  := protocolVersion(.ProtoMajor, .ProtoMinor);  != "" {
		.SetAttrs(traces.String(attrNetworkProtocolVersion, ))
	}
	if .StatusCode >= http.StatusBadRequest {
		.SetAttrs(traces.String(attrErrorType, strconv.Itoa(.StatusCode)))
		.SetError(errors.New(http.StatusText(.StatusCode)))
	}

	if .Body == nil ||
		.Body == http.NoBody ||
		.Method == http.MethodHead ||
		.StatusCode == http.StatusSwitchingProtocols {
		.End()
		return , nil
	}

	.Body = &spanBody{
		ReadCloser: .Body,
		ctx:        ,
		sp:         ,
	}
	return , nil
}

func ( *http.Request) string {
	return .Method
}

type spanBody struct {
	io.ReadCloser
	ctx context.Context
	sp  *traces.Span
}

func ( *spanBody) ( []byte) (int, error) {
	,  := .ReadCloser.Read()
	if  != nil {
		if !errors.Is(, io.EOF) {
			.sp.SetError()
		}
		.sp.End(.ctx)
	}
	return , 
}

func ( *spanBody) () error {
	 := .ReadCloser.Close()
	if  != nil {
		.sp.SetError()
	}
	.sp.End(.ctx)
	return 
}