package observability

import (
	"context"
	"errors"
	"github.com/DataDog/datadog-go/v5/statsd"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/codes"
	"time"
)

// RunRetrieval instruments one attempt, not the whole user task.
// The caller owns retry policy and supplies a bounded, cancellable function.
func RunRetrieval(ctx context.Context, m *statsd.Client, fn func(context.Context) error) error {
	ctx, span := otel.Tracer("agent/steps").Start(ctx, "agent.retrieve")
	defer span.End()
	start := time.Now()
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()
	err := fn(ctx)
	if err == nil {
		err = ctx.Err()
	}
	elapsed := time.Since(start)
	outcome := "ok"
	if err != nil {
		outcome = "error"
		// Export safe categories, never raw provider responses or prompts.
		kind := "dependency"
		if errors.Is(err, context.DeadlineExceeded) {
			kind = "timeout"
		}
		span.SetStatus(codes.Error, kind)
		span.SetAttributes(attribute.String("error.type", kind))
	}
	span.SetAttributes(
		attribute.String("agent.step", "retrieve"),
		attribute.String("agent.outcome", outcome),
		attribute.Bool("agent.latency_breach", elapsed > 1500*time.Millisecond),
		attribute.String("obs.contract_version", "1.0"),
	)
	tags := []string{"service:agent-worker", "env:production", "step:retrieve"}
	// Counts are emitted for every attempt, independently of trace sampling.
	failures := int64(0)
	if err != nil {
		failures = 1
	}
	metricErr := errors.Join(
		m.Count("agent.step.calls", 1, tags, 1),
		m.Count("agent.step.errors", failures, tags, 1),
		m.Distribution("agent.step.duration_seconds", elapsed.Seconds(), tags, 1),
	)
	if metricErr != nil {
		// Route exporter health to a separate, rate-limited diagnostic sink.
		span.SetAttributes(attribute.Bool("obs.metric_enqueue_failed", true))
	}
	return err
}
