package push

import (
	
	

	
	
)

// NotificationProcessor defines the interface for push notification processors.
type NotificationProcessor interface {
	// GetHandler returns the handler for a specific push notification name.
	GetHandler(pushNotificationName string) NotificationHandler
	// ProcessPendingNotifications checks for and processes any pending push notifications.
	// To be used when it is known that there are notifications on the socket.
	// It will try to read from the socket and if it is empty - it may block.
	ProcessPendingNotifications(ctx context.Context, handlerCtx NotificationHandlerContext, rd *proto.Reader) error
	// RegisterHandler registers a handler for a specific push notification name.
	RegisterHandler(pushNotificationName string, handler NotificationHandler, protected bool) error
	// UnregisterHandler removes a handler for a specific push notification name.
	UnregisterHandler(pushNotificationName string) error
}

// Processor handles push notifications with a registry of handlers
type Processor struct {
	registry *Registry
}

type timeoutError interface {
	Timeout() bool
}

func isTimeoutError( error) bool {
	var  timeoutError
	return errors.As(, &) && .Timeout()
}

// NewProcessor creates a new push notification processor
func () *Processor {
	return &Processor{
		registry: NewRegistry(),
	}
}

// GetHandler returns the handler for a specific push notification name
func ( *Processor) ( string) NotificationHandler {
	return .registry.GetHandler()
}

// RegisterHandler registers a handler for a specific push notification name
func ( *Processor) ( string,  NotificationHandler,  bool) error {
	return .registry.RegisterHandler(, , )
}

// UnregisterHandler removes a handler for a specific push notification name
func ( *Processor) ( string) error {
	return .registry.UnregisterHandler()
}

// ProcessPendingNotifications checks for and processes any pending push notifications
// This method should be called by the client in WithReader before reading the reply
// It will try to read from the socket and if it is empty - it may block.
func ( *Processor) ( context.Context,  NotificationHandlerContext,  *proto.Reader) error {
	return .processPendingNotifications(, , , false)
}

// ProcessPendingNotificationsBuffered processes one pending push notification
// and then continues only through frames already buffered by that read. It is
// used by callers that have already established socket readiness and must not
// wait for another frame after draining the current batch.
func ( *Processor) (
	 context.Context,  NotificationHandlerContext,  *proto.Reader,
) error {
	return .processPendingNotifications(, , , true)
}

func ( *Processor) (
	 context.Context,
	 NotificationHandlerContext,
	 *proto.Reader,
	 bool,
) error {
	if  == nil {
		return nil
	}

	 := false
	for ! || ! || .Buffered() > 0 {
		// Check if there's data available to read
		var  byte
		if  {
			for {
				,  := .Peek(1)
				if  != nil {
					if isTimeoutError() {
						return nil
					}
					return 
				}
				 = [0]
				if  != proto.RespAttr {
					break
				}
				// Unlike Peek, DiscardNext consumes bytes. Any error here is
				// fatal because the reader may be left mid-frame.
				if  := .DiscardNext();  != nil {
					return 
				}
			}
		} else {
			var  error
			,  = .PeekReplyType()
			if  != nil {
				// No more data available or error reading.
				break
			}
		}

		// Only process push notifications (arrays starting with >)
		if  != proto.RespPush {
			break
		}

		// see if we should skip this notification
		,  := .PeekPushNotificationName()
		if  != nil {
			// A buffered probe stops cleanly when no full frame is available yet.
			if  && isTimeoutError() {
				return nil
			}
			// The frame is a CONFIRMED push (peeked above) but its name cannot be
			// peeked — too long, or a non-string / malformed name. Fall through to
			// ReadReply to CONSUME it. Do NOT break: that leaves the push at the
			// buffer head for the caller's reply read to eat as the command value
			// (cache poison / one-frame reply shift). A genuine mid-frame read error
			// surfaces at ReadReply below (fatal → the reply-expected drain retires
			// the conn); a non-string name is gracefully ignored (the type assertion
			// below fails, so no handler runs).
		} else if willHandleNotificationInClient() {
			break
		}

		// Surface a ReadReply error (unlike the boundary peek errors above,
		// which consumed nothing): it happens mid-frame after bytes are
		// consumed, so the conn is desynced and the CSC drainer must remove it.
		// Normal reply-read callers log-and-ignore this and let their own read fail.
		,  := .ReadReply()
		if  != nil {
			internal.Logger.Printf(, "push: error reading push notification: %v", )
			return 
		}
		 = true

		// Convert to slice of interfaces
		,  := .([]interface{})
		if ! {
			break
		}

		// Handle the notification directly
		if len() > 0 {
			// Extract the notification type (first element)
			if ,  := [0].(string);  {
				// Get the handler for this notification type
				if  := .registry.GetHandler();  != nil {
					// Handle the notification
					 := .HandlePushNotification(, , )
					if  != nil {
						internal.Logger.Printf(, "push: error handling push notification: %v", )
					}
				}
			}
		}
	}

	return nil
}

// VoidProcessor discards all push notifications without processing them
type VoidProcessor struct{}

// NewVoidProcessor creates a new void push notification processor
func () *VoidProcessor {
	return &VoidProcessor{}
}

// GetHandler returns nil for void processor since it doesn't maintain handlers
func ( *VoidProcessor) ( string) NotificationHandler {
	return nil
}

// RegisterHandler returns an error for void processor since it doesn't maintain handlers
func ( *VoidProcessor) ( string,  NotificationHandler,  bool) error {
	return ErrVoidProcessorRegister()
}

// UnregisterHandler returns an error for void processor since it doesn't maintain handlers
func ( *VoidProcessor) ( string) error {
	return ErrVoidProcessorUnregister()
}

// ProcessPendingNotifications for VoidProcessor does nothing since push notifications
// are only available in RESP3 and this processor is used for RESP2 connections.
// This avoids unnecessary buffer scanning overhead.
// It does however read and discard all push notifications from the buffer to avoid
// them being interpreted as a reply.
// This method should be called by the client in WithReader before reading the reply
// to be sure there are no buffered push notifications.
// It will try to read from the socket and if it is empty - it may block.
func ( *VoidProcessor) ( context.Context,  NotificationHandlerContext,  *proto.Reader) error {
	// read and discard all push notifications
	if  == nil {
		return nil
	}

	for {
		// Check if there's data available to read
		,  := .PeekReplyType()
		if  != nil {
			// No more data available or error reading
			// if timeout, it will be handled by the caller
			break
		}

		// Only process push notifications (arrays starting with >)
		if  != proto.RespPush {
			break
		}
		// see if we should skip this notification
		,  := .PeekPushNotificationName()
		if  != nil {
			// Name too long to peek: still consume the frame below so it isn't
			// misread as a reply.
			if !errors.Is(, proto.ErrPushNotificationNameTooLong) {
				break
			}
		} else if willHandleNotificationInClient() {
			break
		}

		// Read the push notification
		_,  = .ReadReply()
		if  != nil {
			internal.Logger.Printf(context.Background(), "push: error reading push notification: %v", )
			return nil
		}
	}
	return nil
}

// willHandleNotificationInClient checks if a notification type should be ignored by the push notification
// processor and handled by other specialized systems instead (pub/sub, streams, keyspace, etc.).
func willHandleNotificationInClient( string) bool {
	switch  {
	// Pub/Sub notifications - handled by pub/sub system
	case "message", // Regular pub/sub message
		"pmessage",     // Pattern pub/sub message
		"subscribe",    // Subscription confirmation
		"unsubscribe",  // Unsubscription confirmation
		"psubscribe",   // Pattern subscription confirmation
		"punsubscribe", // Pattern unsubscription confirmation
		"smessage",     // Sharded pub/sub message (Redis 7.0+)
		"ssubscribe",   // Sharded subscription confirmation
		"sunsubscribe": // Sharded unsubscription confirmation
		return true
	default:
		return false
	}
}