package maintnotifications

import (
	
	
	
	
	
	

	
	
	
)

// PoolNameMain is the name used for the main connection pool in metrics.
const PoolNameMain = "main"

// handoffWorkerManager manages background workers and queue for connection handoffs
type handoffWorkerManager struct {
	// Event-driven handoff support
	handoffQueue chan HandoffRequest // Queue for handoff requests
	shutdown     chan struct{}       // Shutdown signal
	shutdownOnce sync.Once           // Ensure clean shutdown
	workerWg     sync.WaitGroup      // Track worker goroutines

	// On-demand worker management
	maxWorkers     int
	activeWorkers  atomic.Int32
	workerTimeout  time.Duration // How long workers wait for work before exiting
	workersScaling atomic.Bool

	// Simple state tracking
	pending sync.Map // map[uint64]int64 (connID -> seqID)

	// Configuration for the maintenance notifications
	config *Config

	// Pool hook reference for handoff processing
	poolHook *PoolHook

	// Circuit breaker manager for endpoint failure handling
	circuitBreakerManager *CircuitBreakerManager
}

// newHandoffWorkerManager creates a new handoff worker manager
func newHandoffWorkerManager( *Config,  *PoolHook) *handoffWorkerManager {
	return &handoffWorkerManager{
		handoffQueue:          make(chan HandoffRequest, .HandoffQueueSize),
		shutdown:              make(chan struct{}),
		maxWorkers:            .MaxWorkers,
		activeWorkers:         atomic.Int32{},   // Start with no workers - create on demand
		workerTimeout:         15 * time.Second, // Workers exit after 15s of inactivity
		config:                ,
		poolHook:              ,
		circuitBreakerManager: newCircuitBreakerManager(),
	}
}

// getCurrentWorkers returns the current number of active workers (for testing)
func ( *handoffWorkerManager) () int {
	return int(.activeWorkers.Load())
}

// getPendingMap returns the pending map for testing purposes
func ( *handoffWorkerManager) () *sync.Map {
	return &.pending
}

// getMaxWorkers returns the max workers for testing purposes
func ( *handoffWorkerManager) () int {
	return .maxWorkers
}

// getHandoffQueue returns the handoff queue for testing purposes
func ( *handoffWorkerManager) () chan HandoffRequest {
	return .handoffQueue
}

// getCircuitBreakerStats returns circuit breaker statistics for monitoring
func ( *handoffWorkerManager) () []CircuitBreakerStats {
	return .circuitBreakerManager.GetAllStats()
}

// resetCircuitBreakers resets all circuit breakers (useful for testing)
func ( *handoffWorkerManager) () {
	.circuitBreakerManager.Reset()
}

// isHandoffPending returns true if the given connection has a pending handoff
func ( *handoffWorkerManager) ( *pool.Conn) bool {
	,  := .pending.Load(.GetID())
	return 
}

// ensureWorkerAvailable ensures at least one worker is available to process requests
// Creates a new worker if needed and under the max limit
func ( *handoffWorkerManager) () {
	select {
	case <-.shutdown:
		return
	default:
		if .workersScaling.CompareAndSwap(false, true) {
			defer .workersScaling.Store(false)
			// Check if we need a new worker
			 := .activeWorkers.Load()
			 := 
			for  < int32(.maxWorkers) {
				.workerWg.Add(1)
				go .onDemandWorker()
				++
			}
			// workersWas is always <= currentWorkers
			// currentWorkers will be maxWorkers, but if we have a worker that was closed
			// while we were creating new workers, just add the difference between
			// the currentWorkers and the number of workers we observed initially (i.e. the number of workers we created)
			.activeWorkers.Add( - )
		}
	}
}

// onDemandWorker processes handoff requests and exits when idle
func ( *handoffWorkerManager) () {
	defer func() {
		// Handle panics to ensure proper cleanup
		if  := recover();  != nil {
			internal.Logger.Printf(context.Background(), "%s", logs.WorkerPanicRecovered())
		}

		// Decrement active worker count when exiting
		.activeWorkers.Add(-1)
		.workerWg.Done()
	}()

	// Create reusable timer to prevent timer leaks
	 := time.NewTimer(.workerTimeout)
	defer .Stop()

	for {
		// Reset timer for next iteration
		if !.Stop() {
			select {
			case <-.C:
			default:
			}
		}
		.Reset(.workerTimeout)

		select {
		case <-.shutdown:
			if internal.LogLevel.InfoOrAbove() {
				internal.Logger.Printf(context.Background(), "%s", logs.WorkerExitingDueToShutdown())
			}
			return
		case <-.C:
			// Worker has been idle for too long, exit to save resources
			if internal.LogLevel.InfoOrAbove() {
				internal.Logger.Printf(context.Background(), "%s", logs.WorkerExitingDueToInactivityTimeout(.workerTimeout))
			}
			return
		case  := <-.handoffQueue:
			// Check for shutdown before processing
			select {
			case <-.shutdown:
				if internal.LogLevel.InfoOrAbove() {
					internal.Logger.Printf(context.Background(), "%s", logs.WorkerExitingDueToShutdownWhileProcessing())
				}
				// Clean up the request before exiting
				.pending.Delete(.ConnID)
				return
			default:
				// Process the request
				.processHandoffRequest()
			}
		}
	}
}

// processHandoffRequest processes a single handoff request
func ( *handoffWorkerManager) ( HandoffRequest) {
	if internal.LogLevel.InfoOrAbove() {
		internal.Logger.Printf(context.Background(), "%s", logs.HandoffStarted(.Conn.GetID(), .Endpoint))
	}

	// Create a context with handoff timeout from config
	 := 15 * time.Second // Default timeout
	if .config != nil && .config.HandoffTimeout > 0 {
		 = .config.HandoffTimeout
	}
	,  := context.WithTimeout(context.Background(), )
	defer ()

	// Create a context that also respects the shutdown signal
	,  := context.WithCancel()
	defer ()

	// Monitor shutdown signal in a separate goroutine
	go func() {
		select {
		case <-.shutdown:
			()
		case <-.Done():
		}
	}()

	// Perform the handoff with cancellable context
	,  := .performConnectionHandoff(, .Conn)
	 := 500 * time.Millisecond
	if  != nil {
		if  {
			 := time.Now()
			,  := .Deadline()
			 :=  / 3
			if ! || .Before() {
				// wait half the timeout before retrying if no deadline or deadline has passed
				 = .Add()
			}
			 := .Sub()
			if  <  {
				 = 
			}

			if internal.LogLevel.InfoOrAbove() {
				// Get current retry count for better logging
				 := .Conn.HandoffRetries()
				 := 3 // Default fallback
				if .config != nil {
					 = .config.MaxHandoffRetries
				}
				internal.Logger.Printf(context.Background(), "%s", logs.HandoffFailed(.ConnID, .Endpoint, , , ))
			}
			// Schedule retry - keep connection in pending map until retry is queued
			time.AfterFunc(, func() {
				if  := .queueHandoff(.Conn);  != nil {
					if internal.LogLevel.WarnOrAbove() {
						internal.Logger.Printf(context.Background(), "%s", logs.CannotQueueHandoffForRetry())
					}
					// Failed to queue retry - remove from pending and close connection
					.pending.Delete(.Conn.GetID())
					.closeConnFromRequest(context.Background(), , )
				} else {
					// Successfully queued retry - remove from pending (will be re-added by queueHandoff)
					.pending.Delete(.Conn.GetID())
				}
			})
			return
		} else {
			// Won't retry - remove from pending and close connection
			.pending.Delete(.Conn.GetID())
			go .closeConnFromRequest(, , )
		}

		// Clear handoff state if not returned for retry
		 := .Conn.GetMovingSeqID()
		 := .Conn.GetID()
		if .poolHook.operationsManager != nil {
			.poolHook.operationsManager.UntrackOperationWithConnID(, )
		}
	} else {
		// Success - remove from pending map
		.pending.Delete(.Conn.GetID())
	}
}

// queueHandoff queues a handoff request for processing
// if err is returned, connection will be removed from pool
func ( *handoffWorkerManager) ( *pool.Conn) error {
	// Get handoff info atomically to prevent race conditions
	, ,  := .GetHandoffInfo()

	// on retries the connection will not be marked for handoff, but it will have retries > 0
	// if shouldHandoff is false and retries is 0, then we are not retrying and not do a handoff
	if ! && .HandoffRetries() == 0 {
		if internal.LogLevel.InfoOrAbove() {
			internal.Logger.Printf(context.Background(), "%s", logs.ConnectionNotMarkedForHandoff(.GetID()))
		}
		return errors.New(logs.ConnectionNotMarkedForHandoffError(.GetID()))
	}

	// Create handoff request with atomically retrieved data
	 := HandoffRequest{
		Conn:     ,
		ConnID:   .GetID(),
		Endpoint: ,
		SeqID:    ,
		Pool:     .poolHook.pool, // Include pool for connection removal on failure
	}

	select {
	// priority to shutdown
	case <-.shutdown:
		return ErrShutdown
	default:
		select {
		case <-.shutdown:
			return ErrShutdown
		case .handoffQueue <- :
			// Store in pending map
			.pending.Store(.ConnID, .SeqID)
			// Ensure we have a worker to process this request
			.ensureWorkerAvailable()
			return nil
		default:
			select {
			case <-.shutdown:
				return ErrShutdown
			case .handoffQueue <- :
				// Store in pending map
				.pending.Store(.ConnID, .SeqID)
				// Ensure we have a worker to process this request
				.ensureWorkerAvailable()
				return nil
			case <-time.After(100 * time.Millisecond): // give workers a chance to process
				// Queue is full - log and attempt scaling
				 := len(.handoffQueue)
				 := cap(.handoffQueue)
				if internal.LogLevel.WarnOrAbove() {
					internal.Logger.Printf(context.Background(), "%s", logs.HandoffQueueFull(, ))
				}
			}
		}
	}

	// Ensure we have workers available to handle the load
	.ensureWorkerAvailable()
	return ErrHandoffQueueFull
}

// shutdownWorkers gracefully shuts down the worker manager, waiting for workers to complete
func ( *handoffWorkerManager) ( context.Context) error {
	.shutdownOnce.Do(func() {
		close(.shutdown)
		// workers will exit when they finish their current request

		// Shutdown circuit breaker manager cleanup goroutine
		if .circuitBreakerManager != nil {
			.circuitBreakerManager.Shutdown()
		}
	})

	// Wait for workers to complete
	 := make(chan struct{})
	go func() {
		.workerWg.Wait()
		close()
	}()

	select {
	case <-:
		return nil
	case <-.Done():
		return .Err()
	}
}

// performConnectionHandoff performs the actual connection handoff
// When error is returned, the connection handoff should be retried if err is not ErrMaxHandoffRetriesReached
func ( *handoffWorkerManager) ( context.Context,  *pool.Conn) ( bool,  error) {
	// Clear handoff state after successful handoff
	 := .GetID()

	 := .GetHandoffEndpoint()
	if  == "" {
		return false, ErrConnectionInvalidHandoffState
	}

	// Use circuit breaker to protect against failing endpoints
	 := .circuitBreakerManager.GetCircuitBreaker()

	// Check if circuit breaker is open before attempting handoff
	if .IsOpen() {
		internal.Logger.Printf(, "%s", logs.CircuitBreakerOpen(, ))
		return false, ErrCircuitBreakerOpen // Don't retry when circuit breaker is open
	}

	// Perform the handoff
	,  = .performHandoffInternal(, , , )

	// Update circuit breaker based on result
	if  != nil {
		// Only track dial/network errors in circuit breaker, not initialization errors
		if  {
			.recordFailure()
		}
		return , 
	}

	// Success - record in circuit breaker
	.recordSuccess()
	return false, nil
}

// performHandoffInternal performs the actual handoff logic (extracted for circuit breaker integration)
func ( *handoffWorkerManager) (
	 context.Context,
	 *pool.Conn,
	 string,
	 uint64,
) ( bool,  error) {
	 := .IncrementAndGetHandoffRetries(1)
	internal.Logger.Printf(, "%s", logs.HandoffRetryAttempt(, , , .RemoteAddr().String()))
	 := 3 // Default fallback
	if .config != nil {
		 = .config.MaxHandoffRetries
	}

	if  >  {
		if internal.LogLevel.WarnOrAbove() {
			internal.Logger.Printf(, "%s", logs.ReachedMaxHandoffRetries(, , ))
		}
		// won't retry on ErrMaxHandoffRetriesReached
		return false, ErrMaxHandoffRetriesReached
	}

	// Create endpoint-specific dialer
	 := .createEndpointDialer()

	// Create new connection to the new endpoint
	,  := ()
	if  != nil {
		internal.Logger.Printf(, "%s", logs.FailedToDialNewEndpoint(, , ))
		// will retry
		// Maybe a network error - retry after a delay
		return true, 
	}

	// Get the old connection
	 := .GetNetConn()

	// Apply relaxed timeout to the new connection for the configured post-handoff duration
	// This gives the new connection more time to handle operations during cluster transition
	// Setting this here (before initing the connection) ensures that the connection is going
	// to use the relaxed timeout for the first operation (auth/ACL select)
	if .config != nil && .config.PostHandoffRelaxedDuration > 0 {
		 := .config.RelaxedTimeout
		// Set relaxed timeout with deadline - no background goroutine needed
		 := time.Now().Add(.config.PostHandoffRelaxedDuration)
		.SetRelaxedTimeoutWithDeadline(, , )

		// Record relaxed timeout metric (post-handoff)
		if  := pool.GetMetricConnectionRelaxedTimeoutCallback();  != nil {
			(, 1, , PoolNameMain, "HANDOFF")
		}

		if internal.LogLevel.InfoOrAbove() {
			internal.Logger.Printf(context.Background(), "%s", logs.ApplyingRelaxedTimeoutDueToPostHandoff(, , .Format("15:04:05.000")))
		}
	}

	// Replace the connection and execute initialization
	 = .SetNetConnAndInitConn(, )
	if  != nil {
		// won't retry
		// Initialization failed - remove the connection
		return false, 
	}
	defer func() {
		if  != nil {
			.Close()
		}
	}()

	// Clear handoff state will:
	// - set the connection as usable again
	// - clear the handoff state (shouldHandoff, endpoint, seqID)
	// - reset the handoff retries to 0
	// Note: Theoretically there may be a short window where the connection is in the pool
	// and IDLE (initConn completed) but still has handoff state set.
	.ClearHandoffState()
	internal.Logger.Printf(, "%s", logs.HandoffSucceeded(, ))

	// successfully completed the handoff, no retry needed and no error
	// Notify metrics: connection handoff succeeded
	if  := pool.GetMetricConnectionHandoffCallback();  != nil {
		(, , PoolNameMain)
	}

	return false, nil
}

// createEndpointDialer creates a dialer function that connects to a specific endpoint
func ( *handoffWorkerManager) ( string) func(context.Context) (net.Conn, error) {
	return func( context.Context) (net.Conn, error) {
		// Parse endpoint to extract host and port
		, ,  := net.SplitHostPort()
		if  != nil {
			// If no port specified, assume default Redis port
			 = 
			if  == "" {
				 = "6379"
			}
		}

		// Use the base dialer to connect to the new endpoint
		return .poolHook.baseDialer(, .poolHook.network, net.JoinHostPort(, ))
	}
}

// closeConnFromRequest closes the connection and logs the reason
func ( *handoffWorkerManager) ( context.Context,  HandoffRequest,  error) {
	 := .Pool
	 := .Conn

	// Clear handoff state before closing
	.ClearHandoffState()

	if  != nil {
		// Use RemoveWithoutTurn instead of Remove to avoid freeing a turn that we don't have.
		// The handoff worker doesn't call Get(), so it doesn't have a turn to free.
		// Remove() is meant to be called after Get() and frees a turn.
		// RemoveWithoutTurn() removes and closes the connection without affecting the queue.
		.RemoveWithoutTurn(, , )
		if internal.LogLevel.WarnOrAbove() {
			internal.Logger.Printf(, "%s", logs.RemovingConnectionFromPool(.GetID(), ))
		}
	} else {
		 := .Close() // Close the connection if no pool provided
		if  != nil {
			internal.Logger.Printf(, "redis: failed to close connection: %v", )
		}
		if internal.LogLevel.WarnOrAbove() {
			internal.Logger.Printf(, "%s", logs.NoPoolProvidedCannotRemove(.GetID(), ))
		}
	}
}