package redis

import (
	
	
	

	
	
)

// ErrorTypeNil is the error type reported to OTelRecorder.RecordError for a Nil reply.
const ErrorTypeNil = "NIL"

// ConnInfo provides information about a Redis connection for metrics.
type ConnInfo interface {
	RemoteAddr() net.Addr
	PoolName() string
}

type Pooler interface {
	PoolStats() *pool.Stats
}

type PubSubPooler interface {
	Stats() *pool.PubSubStats
}

// OTelRecorder is the interface for recording OpenTelemetry metrics.

type OTelRecorder interface {
	// RecordOperationDuration records the total operation duration (including all retries)
	RecordOperationDuration(ctx context.Context, duration time.Duration, cmd Cmder, attempts int, err error, cn ConnInfo, dbIndex int)

	// RecordPipelineOperationDuration records the total pipeline/transaction duration.
	// operationName should be "PIPELINE" for regular pipelines or "MULTI" for transactions.
	RecordPipelineOperationDuration(ctx context.Context, duration time.Duration, operationName string, cmdCount int, attempts int, err error, cn ConnInfo, dbIndex int)

	// RecordConnectionCreateTime records the time it took to create a new connection
	RecordConnectionCreateTime(ctx context.Context, duration time.Duration, cn ConnInfo)

	// RecordConnectionRelaxedTimeout records when connection timeout is relaxed/unrelaxed
	// delta: +1 for relaxed, -1 for unrelaxed
	// poolName: name of the connection pool (e.g., "main", "pubsub")
	// notificationType: the notification type that triggered the timeout relaxation (e.g., "MOVING", "HANDOFF")
	RecordConnectionRelaxedTimeout(ctx context.Context, delta int, cn ConnInfo, poolName, notificationType string)

	// RecordConnectionHandoff records when a connection is handed off to another node
	// poolName: name of the connection pool (e.g., "main", "pubsub")
	RecordConnectionHandoff(ctx context.Context, cn ConnInfo, poolName string)

	// RecordError records client errors (ASK, MOVED, handshake failures, etc.)
	// errorType: type of error (e.g., "ASK", "MOVED", "HANDSHAKE_FAILED")
	// statusCode: Redis response status code if available (e.g., "MOVED", "ASK")
	// isInternal: whether this is an internal error
	// retryAttempts: number of retry attempts made
	RecordError(ctx context.Context, errorType string, cn ConnInfo, statusCode string, isInternal bool, retryAttempts int)

	// RecordMaintenanceNotification records when a maintenance notification is received
	// notificationType: the type of notification (e.g., "MOVING", "MIGRATING", etc.)
	RecordMaintenanceNotification(ctx context.Context, cn ConnInfo, notificationType string)

	// RecordConnectionWaitTime records the time spent waiting for a connection from the pool
	RecordConnectionWaitTime(ctx context.Context, duration time.Duration, cn ConnInfo)

	// RecordConnectionClosed records when a connection is closed
	// reason: reason for closing (e.g., "idle", "max_lifetime", "error", "pool_closed")
	// err: the error that caused the close (nil for non-error closures)
	RecordConnectionClosed(ctx context.Context, cn ConnInfo, reason string, err error)

	// RecordPubSubMessage records a Pub/Sub message
	// direction: "sent" or "received"
	// channel: channel name (may be hidden for cardinality reduction)
	// sharded: true for sharded pub/sub (SPUBLISH/SSUBSCRIBE)
	RecordPubSubMessage(ctx context.Context, cn ConnInfo, direction, channel string, sharded bool)

	// RecordStreamLag records the lag for stream consumer group processing
	// lag: time difference between message creation and consumption
	// streamName: name of the stream (may be hidden for cardinality reduction)
	// consumerGroup: name of the consumer group
	// consumerName: name of the consumer
	RecordStreamLag(ctx context.Context, lag time.Duration, cn ConnInfo, streamName, consumerGroup, consumerName string)
}

// OTelConnectionCounter is an optional capability interface for recording
// connection count and pending request changes via UpDownCounters.
// Implementations of OTelRecorder can optionally implement this interface
// to receive connection count and pending request delta notifications.
// This is kept separate from OTelRecorder to avoid breaking existing
// third-party implementations when new methods are added.
type OTelConnectionCounter interface {
	// RecordConnectionCount records a change in connection count (UpDownCounter)
	// delta: +1 when connection added, -1 when connection removed
	// state: connection state (e.g., "idle", "used")
	// isPubSub: true if this is a PubSub connection
	RecordConnectionCount(ctx context.Context, delta int, cn ConnInfo, state string, isPubSub bool)

	// RecordPendingRequests records a change in pending requests (UpDownCounter)
	// delta: +1 when request starts waiting, -1 when request stops waiting
	// poolName is passed explicitly because we may not have a connection yet when request starts
	RecordPendingRequests(ctx context.Context, delta int, cn ConnInfo, poolName string)
}

// This is used for async gauge metrics that need to pull stats from pools periodically.
type OTelPoolRegistrar interface {
	// RegisterPool is called when a new client is created with its main connection pool.
	// poolName: unique identifier for the pool (e.g., "main_abc123")
	RegisterPool(poolName string, pool Pooler)
	// UnregisterPool is called when a client is closed to remove its pool from the registry.
	UnregisterPool(pool Pooler)
	// RegisterPubSubPool is called when a new client is created with a PubSub pool.
	// poolName: unique identifier for the pool (e.g., "main_abc123_pubsub")
	RegisterPubSubPool(poolName string, pool PubSubPooler)
	// UnregisterPubSubPool is called when a PubSub client is closed to remove its pool.
	UnregisterPubSubPool(pool PubSubPooler)
}

// SetOTelRecorder sets the global OpenTelemetry recorder.
func ( OTelRecorder) {
	if  == nil {
		otel.SetGlobalRecorder(nil)
		return
	}
	otel.SetGlobalRecorder(&otelRecorderAdapter{})
}

type otelRecorderAdapter struct {
	recorder OTelRecorder
}

// toConnInfo converts *pool.Conn to ConnInfo interface properly.
// This ensures that a nil *pool.Conn becomes a true nil interface,
// not a non-nil interface containing a nil pointer.
func toConnInfo( *pool.Conn) ConnInfo {
	if  == nil {
		return nil
	}
	return 
}

func ( *otelRecorderAdapter) ( context.Context,  time.Duration,  otel.Cmder,  int,  error,  *pool.Conn,  int) {
	// Convert internal Cmder to public Cmder
	if ,  := .(Cmder);  {
		.recorder.RecordOperationDuration(, , , , , toConnInfo(), )
	}
}

func ( *otelRecorderAdapter) ( context.Context,  time.Duration,  string,  int,  int,  error,  *pool.Conn,  int) {
	.recorder.RecordPipelineOperationDuration(, , , , , , toConnInfo(), )
}

func ( *otelRecorderAdapter) ( context.Context,  time.Duration,  *pool.Conn) {
	.recorder.RecordConnectionCreateTime(, , toConnInfo())
}

func ( *otelRecorderAdapter) ( context.Context,  int,  *pool.Conn, ,  string) {
	.recorder.RecordConnectionRelaxedTimeout(, , toConnInfo(), , )
}

func ( *otelRecorderAdapter) ( context.Context,  *pool.Conn,  string) {
	.recorder.RecordConnectionHandoff(, toConnInfo(), )
}

func ( *otelRecorderAdapter) ( context.Context,  string,  *pool.Conn,  string,  bool,  int) {
	.recorder.RecordError(, , toConnInfo(), , , )
}

func ( *otelRecorderAdapter) ( context.Context,  *pool.Conn,  string) {
	.recorder.RecordMaintenanceNotification(, toConnInfo(), )
}

func ( *otelRecorderAdapter) ( context.Context,  time.Duration,  *pool.Conn) {
	.recorder.RecordConnectionWaitTime(, , toConnInfo())
}

func ( *otelRecorderAdapter) ( context.Context,  *pool.Conn,  string,  error) {
	.recorder.RecordConnectionClosed(, toConnInfo(), , )
}

func ( *otelRecorderAdapter) ( context.Context,  *pool.Conn, ,  string,  bool) {
	.recorder.RecordPubSubMessage(, toConnInfo(), , , )
}

func ( *otelRecorderAdapter) ( context.Context,  time.Duration,  *pool.Conn, , ,  string) {
	.recorder.RecordStreamLag(, , toConnInfo(), , , )
}

func ( *otelRecorderAdapter) ( context.Context,  int,  *pool.Conn,  string,  bool) {
	if ,  := .recorder.(OTelConnectionCounter);  {
		.RecordConnectionCount(, , toConnInfo(), , )
	}
}

func ( *otelRecorderAdapter) ( context.Context,  int,  *pool.Conn,  string) {
	if ,  := .recorder.(OTelConnectionCounter);  {
		.RecordPendingRequests(, , toConnInfo(), )
	}
}

func ( *otelRecorderAdapter) ( string,  pool.Pooler) {
	if ,  := .recorder.(OTelPoolRegistrar);  {
		.RegisterPool(, &poolerAdapter{})
	}
}

func ( *otelRecorderAdapter) ( pool.Pooler) {
	if ,  := .recorder.(OTelPoolRegistrar);  {
		.UnregisterPool(&poolerAdapter{})
	}
}

func ( *otelRecorderAdapter) ( string,  otel.PubSubPooler) {
	if ,  := .recorder.(OTelPoolRegistrar);  {
		.RegisterPubSubPool(, &pubSubPoolerAdapter{})
	}
}

func ( *otelRecorderAdapter) ( otel.PubSubPooler) {
	if ,  := .recorder.(OTelPoolRegistrar);  {
		.UnregisterPubSubPool(&pubSubPoolerAdapter{})
	}
}

type poolerAdapter struct {
	p pool.Pooler
}

func ( *poolerAdapter) () *pool.Stats {
	return .p.Stats()
}

type pubSubPoolerAdapter struct {
	p otel.PubSubPooler
}

func ( *pubSubPoolerAdapter) () *pool.PubSubStats {
	return .p.Stats()
}