package redis

import (
	
	
	

	
	
)

// -------------------------------------------

type JSONCmdable interface {
	JSONArrAppend(ctx context.Context, key, path string, values ...interface{}) *IntSliceCmd
	JSONArrIndex(ctx context.Context, key, path string, value ...interface{}) *IntSliceCmd
	JSONArrIndexWithArgs(ctx context.Context, key, path string, options *JSONArrIndexArgs, value ...interface{}) *IntSliceCmd
	JSONArrInsert(ctx context.Context, key, path string, index int64, values ...interface{}) *IntSliceCmd
	JSONArrLen(ctx context.Context, key, path string) *IntSliceCmd
	JSONArrPop(ctx context.Context, key, path string, index int) *StringSliceCmd
	JSONArrTrim(ctx context.Context, key, path string) *IntSliceCmd
	JSONArrTrimWithArgs(ctx context.Context, key, path string, options *JSONArrTrimArgs) *IntSliceCmd
	JSONClear(ctx context.Context, key, path string) *IntCmd
	JSONDebugMemory(ctx context.Context, key, path string) *IntCmd
	JSONDel(ctx context.Context, key, path string) *IntCmd
	JSONForget(ctx context.Context, key, path string) *IntCmd
	JSONGet(ctx context.Context, key string, paths ...string) *JSONCmd
	JSONGetWithArgs(ctx context.Context, key string, options *JSONGetArgs, paths ...string) *JSONCmd
	JSONMerge(ctx context.Context, key, path string, value string) *StatusCmd
	JSONMSetArgs(ctx context.Context, docs []JSONSetArgs) *StatusCmd
	JSONMSet(ctx context.Context, params ...interface{}) *StatusCmd
	JSONMGet(ctx context.Context, path string, keys ...string) *JSONSliceCmd
	JSONNumIncrBy(ctx context.Context, key, path string, value float64) *JSONCmd
	JSONObjKeys(ctx context.Context, key, path string) *SliceCmd
	JSONObjLen(ctx context.Context, key, path string) *IntPointerSliceCmd
	JSONSet(ctx context.Context, key, path string, value interface{}) *StatusCmd
	JSONSetMode(ctx context.Context, key, path string, value interface{}, mode string) *StatusCmd
	JSONSetWithArgs(ctx context.Context, key, path string, value interface{}, options *JSONSetArgsOptions) *StatusCmd
	JSONStrAppend(ctx context.Context, key, path, value string) *IntPointerSliceCmd
	JSONStrLen(ctx context.Context, key, path string) *IntPointerSliceCmd
	JSONToggle(ctx context.Context, key, path string) *IntPointerSliceCmd
	JSONType(ctx context.Context, key, path string) *JSONSliceCmd
}

type JSONSetArgs struct {
	Key   string
	Path  string
	Value interface{}
}

type JSONArrIndexArgs struct {
	Start int
	Stop  *int
}

type JSONArrTrimArgs struct {
	Start int
	Stop  *int
}

// FPHAType is the floating-point type used for storing FP homogeneous arrays
// in JSON.SET (Redis 8.8+).
type FPHAType string

const (
	FPHATypeBF16 FPHAType = "BF16"
	FPHATypeFP16 FPHAType = "FP16"
	FPHATypeFP32 FPHAType = "FP32"
	FPHATypeFP64 FPHAType = "FP64"
)

// JSONSetArgsOptions are the optional arguments for JSONSetWithArgs.
// Mode is "NX" or "XX" (case-insensitive). FPHA, when set, forces Redis to
// store all FP homogeneous arrays using the specified floating-point type.
type JSONSetArgsOptions struct {
	Mode string
	FPHA FPHAType
}

type JSONCmd struct {
	baseCmd
	val      string
	expanded interface{}
}

var _ Cmder = (*JSONCmd)(nil)

func newJSONCmd( context.Context,  ...interface{}) *JSONCmd {
	return &JSONCmd{
		baseCmd: baseCmd{
			ctx:     ,
			args:    ,
			cmdType: CmdTypeJSON,
		},
	}
}

func ( *JSONCmd) () string {
	.await()
	return cmdString(, .val)
}

func ( *JSONCmd) ( string) {
	.val = 
}

// Val returns the result of the JSON.GET command as a string.
func ( *JSONCmd) () string {
	.await()
	if len(.val) == 0 && .expanded != nil {
		,  := json.Marshal(.expanded)
		if  != nil {
			.SetErr()
			return ""
		}
		return string()

	} else {
		return .val
	}
}

func ( *JSONCmd) () (string, error) {
	.await()
	return .Val(), .Err()
}

// Expanded returns the result of the JSON.GET command as unmarshalled JSON.
func ( *JSONCmd) () (interface{}, error) {
	.await()
	if len(.val) != 0 && .expanded == nil {
		 := json.Unmarshal([]byte(.val), &.expanded)
		if  != nil {
			return nil, 
		}
	}

	return .expanded, nil
}

func ( *JSONCmd) ( *proto.Reader) error {
	// nil response from JSON.(M)GET (cmd.baseCmd.err will be "redis: nil")
	// This happens when the key doesn't exist.
	// Use rawErr() (not Err()): readReply runs inside the batch's Exec, before
	// the autopipeline batch's done channel is closed, so Err()->await() would
	// deadlock on the very Exec that is calling readReply.
	if .baseCmd.rawErr() == Nil {
		.val = ""
		return Nil
	}

	// Handle other base command errors
	if .baseCmd.rawErr() != nil {
		return .baseCmd.rawErr()
	}

	if ,  := .PeekReplyType();  != nil {
		return 
	} else if  == proto.RespArray {

		,  := .ReadArrayLen()
		if  != nil {
			return 
		}

		// Empty array means no results found for JSON path, but key exists
		// This should return "[]", not an error
		if  == 0 {
			.val = "[]"
			return nil
		}

		 := make([]interface{}, )

		for  := 0;  < ; ++ {
			if [],  = .ReadReply();  != nil {
				return 
			}
		}
		.expanded = 

	} else {
		if ,  := .ReadString();  != nil &&  != Nil {
			return 
		} else if  == "" ||  == Nil {
			.val = ""
			return Nil
		} else {
			.val = 
		}
	}

	return nil
}

func ( *JSONCmd) () Cmder {
	return &JSONCmd{
		baseCmd:  .cloneBaseCmd(),
		val:      .val,
		expanded: .expanded, // interface{} can be shared as it should be immutable after parsing
	}
}

// -------------------------------------------

type JSONSliceCmd struct {
	baseCmd
	val []interface{}
}

func ( context.Context,  ...interface{}) *JSONSliceCmd {
	return &JSONSliceCmd{
		baseCmd: baseCmd{
			ctx:     ,
			args:    ,
			cmdType: CmdTypeJSONSlice,
		},
	}
}

func ( *JSONSliceCmd) () string {
	.await()
	return cmdString(, .val)
}

func ( *JSONSliceCmd) ( []interface{}) {
	.val = 
}

func ( *JSONSliceCmd) () []interface{} {
	.await()
	return .val
}

func ( *JSONSliceCmd) () ([]interface{}, error) {
	.await()
	return .val, .err
}

func ( *JSONSliceCmd) ( *proto.Reader) error {
	// rawErr(), not Err(): readReply runs inside Exec before the batch's done
	// channel closes, so Err()->await() would deadlock (see JSONCmd.readReply).
	if .baseCmd.rawErr() == Nil {
		.val = nil
		return Nil
	}

	if ,  := .PeekReplyType();  != nil {
		return 
	} else if  == proto.RespArray {
		,  := .ReadReply()
		if  != nil {
			return 
		} else {
			.val = .([]interface{})
		}

	} else {
		,  := .ReadArrayLen()
		if  != nil {
			return 
		}
		.val = make([]interface{}, )
		for  := 0;  < len(.val); ++ {
			switch ,  := .ReadString(); {
			case  == Nil:
				.val[] = ""
			case  != nil:
				return 
			default:
				.val[] = 
			}
		}
	}
	return nil
}

func ( *JSONSliceCmd) () Cmder {
	var  []interface{}
	if .val != nil {
		 = make([]interface{}, len(.val))
		copy(, .val)
	}
	return &JSONSliceCmd{
		baseCmd: .cloneBaseCmd(),
		val:     ,
	}
}

/*******************************************************************************
*
* IntPointerSliceCmd
* used to represent a RedisJSON response where the result is either an integer or nil
*
*******************************************************************************/

type IntPointerSliceCmd struct {
	baseCmd
	val []*int64
}

// NewIntPointerSliceCmd initialises an IntPointerSliceCmd
func ( context.Context,  ...interface{}) *IntPointerSliceCmd {
	return &IntPointerSliceCmd{
		baseCmd: baseCmd{
			ctx:     ,
			args:    ,
			cmdType: CmdTypeIntPointerSlice,
		},
	}
}

func ( *IntPointerSliceCmd) () string {
	.await()
	return cmdString(, .val)
}

func ( *IntPointerSliceCmd) ( []*int64) {
	.val = 
}

func ( *IntPointerSliceCmd) () []*int64 {
	.await()
	return .val
}

func ( *IntPointerSliceCmd) () ([]*int64, error) {
	.await()
	return .val, .err
}

func ( *IntPointerSliceCmd) ( *proto.Reader) error {
	,  := .ReadArrayLen()
	if  != nil {
		return 
	}
	.val = make([]*int64, )

	for  := 0;  < len(.val); ++ {
		,  := .ReadInt()
		if  != nil &&  != Nil {
			return 
		} else if  != Nil {
			.val[] = &
		}
	}

	return nil
}

func ( *IntPointerSliceCmd) () Cmder {
	var  []*int64
	if .val != nil {
		 = make([]*int64, len(.val))
		copy(, .val)
	}
	return &IntPointerSliceCmd{
		baseCmd: .cloneBaseCmd(),
		val:     ,
	}
}

//------------------------------------------------------------------------------

// JSONArrAppend adds the provided JSON values to the end of the array at the given path.
// For more information, see https://redis.io/commands/json.arrappend
func ( cmdable) ( context.Context, ,  string,  ...interface{}) *IntSliceCmd {
	 := []interface{}{"JSON.ARRAPPEND", , }
	 = append(, ...)
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrIndex searches for the first occurrence of the provided JSON value in the array at the given path.
// For more information, see https://redis.io/commands/json.arrindex
func ( cmdable) ( context.Context, ,  string,  ...interface{}) *IntSliceCmd {
	 := []interface{}{"JSON.ARRINDEX", , }
	 = append(, ...)
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrIndexWithArgs searches for the first occurrence of a JSON value in an array while allowing the start and
// stop options to be provided.
// For more information, see https://redis.io/commands/json.arrindex
func ( cmdable) ( context.Context, ,  string,  *JSONArrIndexArgs,  ...interface{}) *IntSliceCmd {
	 := []interface{}{"JSON.ARRINDEX", , }
	 = append(, ...)

	if  != nil {
		 = append(, .Start)
		if .Stop != nil {
			 = append(, *.Stop)
		}
	}
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrInsert inserts the JSON values into the array at the specified path before the index (shifts to the right).
// For more information, see https://redis.io/commands/json.arrinsert
func ( cmdable) ( context.Context, ,  string,  int64,  ...interface{}) *IntSliceCmd {
	 := []interface{}{"JSON.ARRINSERT", , , }
	 = append(, ...)
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrLen reports the length of the JSON array at the specified path in the given key.
// For more information, see https://redis.io/commands/json.arrlen
func ( cmdable) ( context.Context, ,  string) *IntSliceCmd {
	 := []interface{}{"JSON.ARRLEN", , }
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrPop removes and returns an element from the specified index in the array.
// For more information, see https://redis.io/commands/json.arrpop
func ( cmdable) ( context.Context, ,  string,  int) *StringSliceCmd {
	 := []interface{}{"JSON.ARRPOP", , , }
	 := NewStringSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrTrim trims an array to contain only the specified inclusive range of elements.
// For more information, see https://redis.io/commands/json.arrtrim
func ( cmdable) ( context.Context, ,  string) *IntSliceCmd {
	 := []interface{}{"JSON.ARRTRIM", , }
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONArrTrimWithArgs trims an array to contain only the specified inclusive range of elements.
// For more information, see https://redis.io/commands/json.arrtrim
func ( cmdable) ( context.Context, ,  string,  *JSONArrTrimArgs) *IntSliceCmd {
	 := []interface{}{"JSON.ARRTRIM", , }

	if  != nil {
		 = append(, .Start)

		if .Stop != nil {
			 = append(, *.Stop)
		}
	}
	 := NewIntSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONClear clears container values (arrays/objects) and sets numeric values to 0.
// For more information, see https://redis.io/commands/json.clear
func ( cmdable) ( context.Context, ,  string) *IntCmd {
	 := []interface{}{"JSON.CLEAR", , }
	 := NewIntCmd(, ...)
	_ = (, )
	return 
}

// JSONDebugMemory reports a value's memory usage in bytes (unimplemented)
// For more information, see https://redis.io/commands/json.debug-memory
func ( cmdable) ( context.Context, ,  string) *IntCmd {
	panic("not implemented")
}

// JSONDel deletes a value.
// For more information, see https://redis.io/commands/json.del
func ( cmdable) ( context.Context, ,  string) *IntCmd {
	 := []interface{}{"JSON.DEL", , }
	 := NewIntCmd(, ...)
	_ = (, )
	return 
}

// JSONForget deletes a value.
// For more information, see https://redis.io/commands/json.forget
func ( cmdable) ( context.Context, ,  string) *IntCmd {
	 := []interface{}{"JSON.FORGET", , }
	 := NewIntCmd(, ...)
	_ = (, )
	return 
}

// JSONGet returns the value at path in JSON serialized form. JSON.GET returns an
// array of strings. This function parses out the wrapping array but leaves the
// internal strings unprocessed by default (see Val())
// For more information - https://redis.io/commands/json.get/
func ( cmdable) ( context.Context,  string,  ...string) *JSONCmd {
	 := make([]interface{}, len()+2)
	[0] = "JSON.GET"
	[1] = 
	for ,  := range  {
		[+2] = 
	}
	 := newJSONCmd(, ...)
	_ = (, )
	return 
}

type JSONGetArgs struct {
	Indent  string
	Newline string
	Space   string
}

// JSONGetWithArgs - Retrieves the value of a key from a JSON document.
// This function also allows for specifying additional options such as:
// Indention, NewLine and Space
// For more information - https://redis.io/commands/json.get/
func ( cmdable) ( context.Context,  string,  *JSONGetArgs,  ...string) *JSONCmd {
	 := []interface{}{"JSON.GET", }
	if  != nil {
		if .Indent != "" {
			 = append(, "INDENT", .Indent)
		}
		if .Newline != "" {
			 = append(, "NEWLINE", .Newline)
		}
		if .Space != "" {
			 = append(, "SPACE", .Space)
		}
		for ,  := range  {
			 = append(, )
		}
	}
	 := newJSONCmd(, ...)
	_ = (, )
	return 
}

// JSONMerge merges a given JSON value into matching paths.
// For more information, see https://redis.io/commands/json.merge
func ( cmdable) ( context.Context, ,  string,  string) *StatusCmd {
	 := []interface{}{"JSON.MERGE", , , }
	 := NewStatusCmd(, ...)
	_ = (, )
	return 
}

// JSONMGet returns the values at the specified path from multiple key arguments.
// Note - the arguments are reversed when compared with `JSON.MGET` as we want
// to follow the pattern of having the last argument be variable.
// For more information, see https://redis.io/commands/json.mget
func ( cmdable) ( context.Context,  string,  ...string) *JSONSliceCmd {
	 := make([]interface{}, len()+1)
	[0] = "JSON.MGET"
	for ,  := range  {
		[+1] = 
	}
	 = append(, )
	 := NewJSONSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONMSetArgs sets or updates one or more JSON values according to the specified key-path-value triplets.
// For more information, see https://redis.io/commands/json.mset
func ( cmdable) ( context.Context,  []JSONSetArgs) *StatusCmd {
	 := []interface{}{"JSON.MSET"}
	for ,  := range  {
		 = append(, .Key, .Path, .Value)
	}
	 := NewStatusCmd(, ...)
	_ = (, )
	return 
}

func ( cmdable) ( context.Context,  ...interface{}) *StatusCmd {
	 := []interface{}{"JSON.MSET"}
	 = append(, ...)
	 := NewStatusCmd(, ...)
	_ = (, )
	return 
}

// JSONNumIncrBy increments the number value stored at the specified path by the provided number.
// For more information, see https://redis.io/docs/latest/commands/json.numincrby/
func ( cmdable) ( context.Context, ,  string,  float64) *JSONCmd {
	 := []interface{}{"JSON.NUMINCRBY", , , }
	 := newJSONCmd(, ...)
	_ = (, )
	return 
}

// JSONObjKeys returns the keys in the object that's referenced by the specified path.
// For more information, see https://redis.io/commands/json.objkeys
func ( cmdable) ( context.Context, ,  string) *SliceCmd {
	 := []interface{}{"JSON.OBJKEYS", , }
	 := NewSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONObjLen reports the number of keys in the JSON object at the specified path in the given key.
// For more information, see https://redis.io/commands/json.objlen
func ( cmdable) ( context.Context, ,  string) *IntPointerSliceCmd {
	 := []interface{}{"JSON.OBJLEN", , }
	 := NewIntPointerSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONSet sets the JSON value at the given path in the given key. The value must be something that
// can be marshaled to JSON (using encoding/JSON) unless the argument is a string or a []byte when we assume that
// it can be passed directly as JSON.
// For more information, see https://redis.io/commands/json.set
func ( cmdable) ( context.Context, ,  string,  interface{}) *StatusCmd {
	return .JSONSetMode(, , , , "")
}

// JSONSetMode sets the JSON value at the given path in the given key and allows the mode to be set
// (the mode value must be "XX" or "NX"). The value must be something that can be marshaled to JSON (using encoding/JSON) unless
// the argument is a string or []byte when we assume that it can be passed directly as JSON.
// For more information, see https://redis.io/commands/json.set
func ( cmdable) ( context.Context, ,  string,  interface{},  string) *StatusCmd {
	return .JSONSetWithArgs(, , , , &JSONSetArgsOptions{Mode: })
}

// JSONSetWithArgs sets the JSON value at the given path in the given key with optional arguments
// for setting mode (NX/XX) and the FPHA (Floating-Point Homogeneous Array) type used for storing
// FP arrays. The value must be something that can be marshaled to JSON (using encoding/JSON) unless
// the argument is a string or []byte when we assume that it can be passed directly as JSON.
// For more information, see https://redis.io/commands/json.set
func ( cmdable) ( context.Context, ,  string,  interface{},  *JSONSetArgsOptions) *StatusCmd {
	var  []byte
	var  error
	switch v := .(type) {
	case string:
		 = []byte()
	case []byte:
		 = 
	default:
		,  = json.Marshal()
	}
	 := []interface{}{"JSON.SET", , , util.BytesToString()}
	if  != nil {
		if .Mode != "" {
			switch strings.ToUpper(.Mode) {
			case "XX", "NX":
				 = append(, strings.ToUpper(.Mode))
			default:
				panic("redis: JSON.SET mode must be NX or XX")
			}
		}
		if .FPHA != "" {
			 = append(, "FPHA", string(.FPHA))
		}
	}
	 := NewStatusCmd(, ...)
	if  != nil {
		.SetErr()
	} else {
		_ = (, )
	}
	return 
}

// JSONStrAppend appends the JSON-string values to the string at the specified path.
// For more information, see https://redis.io/commands/json.strappend
func ( cmdable) ( context.Context, , ,  string) *IntPointerSliceCmd {
	 := []interface{}{"JSON.STRAPPEND", , , }
	 := NewIntPointerSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONStrLen reports the length of the JSON String at the specified path in the given key.
// For more information, see https://redis.io/commands/json.strlen
func ( cmdable) ( context.Context, ,  string) *IntPointerSliceCmd {
	 := []interface{}{"JSON.STRLEN", , }
	 := NewIntPointerSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONToggle toggles a Boolean value stored at the specified path.
// For more information, see https://redis.io/commands/json.toggle
func ( cmdable) ( context.Context, ,  string) *IntPointerSliceCmd {
	 := []interface{}{"JSON.TOGGLE", , }
	 := NewIntPointerSliceCmd(, ...)
	_ = (, )
	return 
}

// JSONType reports the type of JSON value at the specified path.
// For more information, see https://redis.io/commands/json.type
func ( cmdable) ( context.Context, ,  string) *JSONSliceCmd {
	 := []interface{}{"JSON.TYPE", , }
	 := NewJSONSliceCmd(, ...)
	_ = (, )
	return 
}