package maintnotifications

import (
	
	
	
	
	
	
	

	
	
	
	
	
)

// Push notification type constants for maintenance
const (
	NotificationMoving      = "MOVING"       // Per-connection handoff notification
	NotificationMigrating   = "MIGRATING"    // Per-connection migration start notification - relaxes timeouts
	NotificationMigrated    = "MIGRATED"     // Per-connection migration complete notification - clears relaxed timeouts
	NotificationFailingOver = "FAILING_OVER" // Per-connection failover start notification - relaxes timeouts
	NotificationFailedOver  = "FAILED_OVER"  // Per-connection failover complete notification - clears relaxed timeouts
	NotificationSMigrating  = "SMIGRATING"   // Cluster slot migrating notification - relaxes timeouts
	NotificationSMigrated   = "SMIGRATED"    // Cluster slot migrated notification -  unrelaxes timeouts and triggers cluster state reload
)

// maintenanceNotificationTypes contains all notification types that maintenance handles
var maintenanceNotificationTypes = []string{
	NotificationMoving,
	NotificationMigrating,
	NotificationMigrated,
	NotificationFailingOver,
	NotificationFailedOver,
	NotificationSMigrating,
	NotificationSMigrated,
}

// NotificationHook is called before and after notification processing
// PreHook can modify the notification and return false to skip processing
// PostHook is called after successful processing
type NotificationHook interface {
	PreHook(ctx context.Context, notificationCtx push.NotificationHandlerContext, notificationType string, notification []interface{}) ([]interface{}, bool)
	PostHook(ctx context.Context, notificationCtx push.NotificationHandlerContext, notificationType string, notification []interface{}, result error)
}

// MovingOperationKey provides a unique key for tracking MOVING operations
// that combines sequence ID with connection identifier to handle duplicate
// sequence IDs across multiple connections to the same node.
type MovingOperationKey struct {
	SeqID  int64  // Sequence ID from MOVING notification
	ConnID uint64 // Unique connection identifier
}

// String returns a string representation of the key for debugging
func ( MovingOperationKey) () string {
	return fmt.Sprintf("seq:%d-conn:%d", .SeqID, .ConnID)
}

// Manager provides a simplified upgrade functionality with hooks and atomic state.
type Manager struct {
	client  interfaces.ClientInterface
	config  *Config
	options interfaces.OptionsInterface
	pool    pool.Pooler

	// MOVING operation tracking - using sync.Map for better concurrent performance
	activeMovingOps sync.Map // map[MovingOperationKey]*MovingOperation

	// SMIGRATED notification deduplication - tracks processed SeqIDs
	// Multiple connections may receive the same SMIGRATED notification
	processedSMigratedSeqIDs sync.Map // map[int64]bool

	// Atomic state tracking - no locks needed for state queries
	activeOperationCount atomic.Int64 // Number of active operations
	closed               atomic.Bool  // Manager closed state

	// shutdownTimeout bounds each pool hook's Shutdown during Close. A field
	// (not a constant) so tests can exercise the failed-Close-then-retry
	// path without waiting out the real budget.
	shutdownTimeout time.Duration

	// Notification hooks for extensibility
	hooks        []NotificationHook
	hooksMu      sync.RWMutex // Protects hooks slice
	poolHooksRef *PoolHook

	// additionalPoolHooks are pool hooks bound to pools other than the primary
	// one (e.g. a dedicated pipeline connection pool). Each is an independent
	// *PoolHook bound to its own pool because the hook's failed-handoff removal
	// target (HandoffRequest.Pool) is taken from the hook's single pool field,
	// so one hook cannot safely serve two pools. They share this Manager as
	// their operations manager, keeping MOVING/MIGRATING tracking centralized.
	additionalPoolHooks []additionalPoolHook

	// Connections that successfully enabled maintnotifications. These need to be
	// retired before the pool-level listeners are removed.
	maintNotificationsConns sync.Map // connID -> *pool.Conn

	// Cluster state reload callback for SMIGRATED notifications.
	// Stored atomically because it is set from the OnNewNode hook while a node
	// client is being created and read from the SMIGRATED push handler on that
	// node's connections, which can overlap during connection init.
	clusterStateReloadCallback atomic.Pointer[ClusterStateReloadCallback]
}

// MovingOperation tracks an active MOVING operation.
type MovingOperation struct {
	SeqID       int64
	NewEndpoint string
	StartTime   time.Time
	Deadline    time.Time
}

// ClusterStateReloadCallback is a callback function that triggers cluster state reload.
// This is used by node clients to notify their parent ClusterClient about SMIGRATED notifications.
// The hostPort parameter indicates the destination node (e.g., "127.0.0.1:6379").
// The slotRanges parameter contains the migrated slots (e.g., ["1234", "5000-6000"]).
// Currently, implementations typically reload the entire cluster state, but in the future
// this could be optimized to reload only the specific slots.
type ClusterStateReloadCallback func(ctx context.Context, hostPort string, slotRanges []string)

// NewManager creates a new simplified manager.
func ( interfaces.ClientInterface,  pool.Pooler,  *Config) (*Manager, error) {
	if  == nil {
		return nil, ErrInvalidClient
	}

	 := &Manager{
		client:          ,
		pool:            ,
		options:         .GetOptions(),
		config:          .Clone(),
		hooks:           make([]NotificationHook, 0),
		shutdownTimeout: 10 * time.Second,
	}

	// Set up push notification handling
	if  := .setupPushNotifications();  != nil {
		return nil, 
	}

	return , nil
}

// GetPoolHook creates a pool hook with a custom dialer.
func ( *Manager) ( func(context.Context, string, string) (net.Conn, error)) {
	 := .createPoolHook()
	.pool.AddPoolHook()
}

// additionalPoolHook pairs a pool hook with the pool it was attached to so the
// manager can shut it down and detach it on Close.
type additionalPoolHook struct {
	pool pool.Pooler
	hook *PoolHook
}

// InitPoolHookForPool attaches a maintnotifications pool hook to an additional
// pool (e.g. a client's dedicated pipeline connection pool). A fresh, independent
// *PoolHook is created and bound to the given pool so that connections which fail
// handoff are removed from the correct pool — the hook's removal target is its own
// single pool field, so the primary hook cannot be reused for a second pool. The
// new hook shares this Manager as its operations manager, so MOVING/MIGRATING
// tracking and notification handling stay centralized across both pools.
func ( *Manager) ( pool.Pooler,  func(context.Context, string, string) (net.Conn, error)) {
	if  == nil {
		return
	}
	 := 0
	 := ""
	if .options != nil {
		 = .options.GetPoolSize()
		 = .options.GetNetwork()
	}
	 := NewPoolHookWithPoolSize(, , .config, , )
	.SetPool()
	// The closed check, the append, AND the AddPoolHook must all be atomic with
	// respect to Close's snapshot: hold the lock across all three so either Close
	// runs first (closed==true here, so we neither register nor attach) or we
	// register+attach first (Close's snapshot then includes this hook and tears
	// it down). Attaching outside the lock left a window where Close could
	// snapshot/tear-down between the append and the attach, then AddPoolHook
	// would re-attach to a closed manager's pool — leaking an active hook.
	// p.AddPoolHook is lock-free (atomic swap on the pool's own hook manager) and
	// never calls back into this manager, so holding hooksMu across it is safe.
	.hooksMu.Lock()
	defer .hooksMu.Unlock()
	if .closed.Load() {
		return
	}
	.additionalPoolHooks = append(.additionalPoolHooks, additionalPoolHook{pool: , hook: })
	.AddPoolHook()
}

// hookForConn returns the pool hook that owns cn's pool: an additional hook
// when the connection came from a secondary pool (e.g. a client's dedicated
// pipeline pool), the primary hook otherwise. Handoffs must be queued through
// the owning hook — the HandoffRequest carries that hook's pool, and a failed
// handoff removes the connection from it, so queuing a pipeline-pool
// connection on the primary hook would close the connection without freeing
// its slot in the pipeline pool's bookkeeping.
func ( *Manager) ( *pool.Conn) *PoolHook {
	if  == nil {
		return .poolHooksRef
	}
	 := .PoolName()
	if  == "" {
		return .poolHooksRef
	}
	.hooksMu.RLock()
	defer .hooksMu.RUnlock()
	for ,  := range .additionalPoolHooks {
		// Pooler does not expose the name; the concrete pool does. A Pooler
		// implementation without it simply never matches and falls through to
		// the primary hook — the pre-existing behavior.
		if ,  := .pool.(interface{ () string });  && .() ==  {
			return .hook
		}
	}
	return .poolHooksRef
}

// setupPushNotifications sets up push notification handling by registering with the client's processor.
func ( *Manager) () error {
	 := .client.GetPushProcessor()
	if  == nil {
		return ErrInvalidClient // Client doesn't support push notifications
	}

	// Create our notification handler
	 := &NotificationHandler{manager: , operationsManager: }

	// Register handlers for all upgrade notifications with the client's processor
	for ,  := range maintenanceNotificationTypes {
		if  := .RegisterHandler(, , true);  != nil {
			return errors.New(logs.FailedToRegisterHandler(, ))
		}
	}

	return nil
}

// TrackMovingOperationWithConnID starts a new MOVING operation with a specific connection ID.
func ( *Manager) ( context.Context,  string,  time.Time,  int64,  uint64) error {
	// Create composite key
	 := MovingOperationKey{
		SeqID:  ,
		ConnID: ,
	}

	// Create MOVING operation record
	 := &MovingOperation{
		SeqID:       ,
		NewEndpoint: ,
		StartTime:   time.Now(),
		Deadline:    ,
	}

	// Use LoadOrStore for atomic check-and-set operation
	if ,  := .activeMovingOps.LoadOrStore(, );  {
		// Duplicate MOVING notification, ignore
		if internal.LogLevel.DebugOrAbove() { // Debug level
			internal.Logger.Printf(context.Background(), "%s", logs.DuplicateMovingOperation(, , ))
		}
		return nil
	}
	if internal.LogLevel.DebugOrAbove() { // Debug level
		internal.Logger.Printf(context.Background(), "%s", logs.TrackingMovingOperation(, , ))
	}

	// Increment active operation count atomically
	.activeOperationCount.Add(1)

	return nil
}

// UntrackOperationWithConnID completes a MOVING operation with a specific connection ID.
func ( *Manager) ( int64,  uint64) {
	// Create composite key
	 := MovingOperationKey{
		SeqID:  ,
		ConnID: ,
	}

	// Remove from active operations atomically
	if ,  := .activeMovingOps.LoadAndDelete();  {
		if internal.LogLevel.DebugOrAbove() { // Debug level
			internal.Logger.Printf(context.Background(), "%s", logs.UntrackingMovingOperation(, ))
		}
		// Decrement active operation count only if operation existed
		.activeOperationCount.Add(-1)
	} else {
		if internal.LogLevel.DebugOrAbove() { // Debug level
			internal.Logger.Printf(context.Background(), "%s", logs.OperationNotTracked(, ))
		}
	}
}

// GetActiveMovingOperations returns active operations with composite keys.
// WARNING: This method creates a new map and copies all operations on every call.
// Use sparingly, especially in hot paths or high-frequency logging.
func ( *Manager) () map[MovingOperationKey]*MovingOperation {
	 := make(map[MovingOperationKey]*MovingOperation)

	// Iterate over sync.Map to build result
	.activeMovingOps.Range(func(,  interface{}) bool {
		 := .(MovingOperationKey)
		 := .(*MovingOperation)

		// Create a copy to avoid sharing references
		[] = &MovingOperation{
			SeqID:       .SeqID,
			NewEndpoint: .NewEndpoint,
			StartTime:   .StartTime,
			Deadline:    .Deadline,
		}
		return true // Continue iteration
	})

	return 
}

// IsHandoffInProgress returns true if any handoff is in progress.
// Uses atomic counter for lock-free operation.
func ( *Manager) () bool {
	return .activeOperationCount.Load() > 0
}

// GetActiveOperationCount returns the number of active operations.
// Uses atomic counter for lock-free operation.
func ( *Manager) () int64 {
	return .activeOperationCount.Load()
}

// MarkSMigratedSeqIDProcessed attempts to mark a SMIGRATED SeqID as processed.
// Returns true if this is the first time processing this SeqID (should process),
// false if it was already processed (should skip).
// This prevents duplicate processing when multiple connections receive the same notification.
func ( *Manager) ( int64) bool {
	,  := .processedSMigratedSeqIDs.LoadOrStore(, true)
	return ! // Return true if NOT already processed
}

// TrackMaintNotificationsConn records a connection that successfully enabled
// maintnotifications so it can be retired if the feature is later disabled for
// the pool.
func ( *Manager) ( *pool.Conn) {
	if  == nil {
		return
	}
	.maintNotificationsConns.Store(.GetID(), )
}

// UntrackMaintNotificationsConn removes a connection from the enabled
// maintnotifications set.
func ( *Manager) ( uint64) {
	.maintNotificationsConns.Delete()
}

func ( *Manager) () []*pool.Conn {
	var  []*pool.Conn
	.maintNotificationsConns.Range(func(,  interface{}) bool {
		if ,  := .(*pool.Conn);  {
			 = append(, )
		}
		return true
	})
	return 
}

func ( *Manager) ( context.Context) {
	 := .maintNotificationsConnSnapshot()
	if len() == 0 {
		return
	}

	// Tracked connections can live in the primary pool OR in any additional
	// pool this manager attached a hook to (e.g. a client's dedicated pipeline
	// connection pool — its conns run initConn and are tracked exactly like
	// primary ones). Retire through every pool: RetireConns skips connections
	// a pool does not own, so offering the full snapshot to each pool is safe.
	// Missing the additional pools left pipeline connections in service with
	// maintnotifications enabled but no hook attached after a runtime
	// downgrade — pushes on them were silently dropped.
	 := make([]pool.Pooler, 0, 1+len(.additionalPoolHooks))
	if .pool != nil {
		 = append(, .pool)
	}
	.hooksMu.RLock()
	for ,  := range .additionalPoolHooks {
		if .pool != nil {
			 = append(, .pool)
		}
	}
	.hooksMu.RUnlock()

	for ,  := range  {
		if ,  := .(pool.ConnRetirer);  {
			.RetireConns(, , pool.CloseReasonMaintNotificationsDisabled)
			continue
		}
		for ,  := range  {
			_ = .CloseConn(, , pool.CloseReasonMaintNotificationsDisabled, pool.MetricStateIdle)
		}
	}
}

// Close closes the manager.
func ( *Manager) () error {
	// Use atomic operation for thread-safe close check
	if !.closed.CompareAndSwap(false, true) {
		return nil // Already closed
	}

	// Retire connections that enabled maintnotifications before removing the
	// pool-level listeners that process those push notifications.
	.retireMaintNotificationsConns(context.Background())

	// Shutdown the pool hook if it exists
	if .poolHooksRef != nil {
		// Use a timeout to prevent hanging indefinitely
		,  := context.WithTimeout(context.Background(), .shutdownTimeout)
		defer ()

		 := .poolHooksRef.Shutdown()
		if  != nil {
			// was not able to close pool hook, keep closed state false
			.closed.Store(false)
			return 
		}
		// Remove the pool hook from the pool
		if .pool != nil {
			.pool.RemovePoolHook(.poolHooksRef)
		}
	}

	// Shutdown and detach any hooks bound to additional pools (e.g. a dedicated
	// pipeline pool). Snapshot under the lock so we don't iterate concurrently
	// with a registering InitPoolHookForPool; Shutdown itself runs unlocked.
	.hooksMu.Lock()
	 := .additionalPoolHooks
	.additionalPoolHooks = nil
	.hooksMu.Unlock()
	for ,  := range  {
		,  := context.WithTimeout(context.Background(), .shutdownTimeout)
		 := .hook.Shutdown()
		()
		if  != nil {
			// Could not cleanly shut down this hook. Put it and the ones not
			// yet processed back so a retried Close still sees them, then stay
			// open so the caller can retry, matching the primary-hook behavior
			// above. Hooks before i already shut down and detached.
			.hooksMu.Lock()
			 := make([]additionalPoolHook, 0, len()-+len(.additionalPoolHooks))
			 = append(, [:]...)
			 = append(, .additionalPoolHooks...)
			.additionalPoolHooks = 
			.hooksMu.Unlock()
			.closed.Store(false)
			return 
		}
		if .pool != nil {
			.pool.RemovePoolHook(.hook)
		}
	}

	// Clear all active operations
	.activeMovingOps.Range(func(,  interface{}) bool {
		.activeMovingOps.Delete()
		return true
	})

	// Reset counter
	.activeOperationCount.Store(0)

	return nil
}

// GetState returns current state using atomic counter for lock-free operation.
func ( *Manager) () State {
	if .activeOperationCount.Load() > 0 {
		return StateMoving
	}
	return StateIdle
}

// processPreHooks calls all pre-hooks and returns the modified notification and whether to continue processing.
func ( *Manager) ( context.Context,  push.NotificationHandlerContext,  string,  []interface{}) ([]interface{}, bool) {
	.hooksMu.RLock()
	defer .hooksMu.RUnlock()

	 := 

	for ,  := range .hooks {
		,  := .PreHook(, , , )
		if ! {
			return , false
		}
		 = 
	}

	return , true
}

// processPostHooks calls all post-hooks with the processing result.
func ( *Manager) ( context.Context,  push.NotificationHandlerContext,  string,  []interface{},  error) {
	.hooksMu.RLock()
	defer .hooksMu.RUnlock()

	for ,  := range .hooks {
		.PostHook(, , , , )
	}
}

// createPoolHook creates a pool hook with this manager already set.
func ( *Manager) ( func(context.Context, string, string) (net.Conn, error)) *PoolHook {
	if .poolHooksRef != nil {
		return .poolHooksRef
	}
	// Get pool size from client options for better worker defaults
	 := 0
	if .options != nil {
		 = .options.GetPoolSize()
	}

	.poolHooksRef = NewPoolHookWithPoolSize(, .options.GetNetwork(), .config, , )
	.poolHooksRef.SetPool(.pool)

	return .poolHooksRef
}

func ( *Manager) ( NotificationHook) {
	.hooksMu.Lock()
	defer .hooksMu.Unlock()
	.hooks = append(.hooks, )
}

// SetClusterStateReloadCallback sets the callback function that will be called when a SMIGRATED notification is received.
// This allows node clients to notify their parent ClusterClient to reload cluster state.
func ( *Manager) ( ClusterStateReloadCallback) {
	.clusterStateReloadCallback.Store(&)
}

// TriggerClusterStateReload calls the cluster state reload callback if it's set.
// This is called when a SMIGRATED notification is received.
func ( *Manager) ( context.Context,  string,  []string) {
	if  := .clusterStateReloadCallback.Load();  != nil {
		(*)(, , )
	}
}