package redis

import (
	
	
	
	
	
	
)

type Scripter interface {
	Eval(ctx context.Context, script string, keys []string, args ...interface{}) *Cmd
	EvalSha(ctx context.Context, sha1 string, keys []string, args ...interface{}) *Cmd
	EvalRO(ctx context.Context, script string, keys []string, args ...interface{}) *Cmd
	EvalShaRO(ctx context.Context, sha1 string, keys []string, args ...interface{}) *Cmd
	ScriptExists(ctx context.Context, hashes ...string) *BoolSliceCmd
	ScriptLoad(ctx context.Context, script string) *StringCmd
}

var (
	_ Scripter = (*Client)(nil)
	_ Scripter = (*Ring)(nil)
	_ Scripter = (*ClusterClient)(nil)
)

type Script struct {
	src       string
	mu        sync.RWMutex
	hash      string
	serverSHA bool // if true: do not compute SHA-1 in Go; load digest from Redis (SCRIPT LOAD)
}

func ( string) *Script {
	 := sha1.New()
	_, _ = io.WriteString(, )

	return &Script{
		src:       ,
		hash:      hex.EncodeToString(.Sum(nil)),
		serverSHA: false,
	}
}

// NewScriptServerSHA creates a Script that avoids computing SHA-1 in Go.
// The digest is obtained from Redis via SCRIPT LOAD (server-side hashing),
// then EVALSHA/EVALSHA_RO is used.
func ( string) *Script {
	return &Script{
		src:       ,
		serverSHA: true,
	}
}

func ( *Script) () string {
	.mu.RLock()
	defer .mu.RUnlock()
	return .hash
}

func ( *Script) ( context.Context,  Scripter) *StringCmd {
	 := .ScriptLoad(, .src)
	if  := .Err();  == nil {
		.mu.Lock()
		.hash = .Val()
		.mu.Unlock()
	}
	return 
}

func ( *Script) ( context.Context,  Scripter) *BoolSliceCmd {
	.mu.RLock()
	 := .hash
	 := .serverSHA
	.mu.RUnlock()
	if  == "" &&  {
		// For server-side scripts, obtain digest from Redis first.
		// If hash is empty, it means SCRIPT LOAD was not called yet, so we check existence of empty hash which will return false.
		// This avoids unnecessary SCRIPT LOAD just to check existence.
		if  := .ensureHash(, );  != nil {
			return .ScriptExists(, "")
		}
		.mu.RLock()
		 = .hash
		.mu.RUnlock()
	}
	if  == "" {
		return .ScriptExists(, "")
	}
	return .ScriptExists(, )
}

func ( *Script) ( context.Context,  Scripter,  []string,  ...interface{}) *Cmd {
	return .Eval(, .src, , ...)
}

func ( *Script) ( context.Context,  Scripter,  []string,  ...interface{}) *Cmd {
	return .EvalRO(, .src, , ...)
}

// ensureHash ensures that s.hash is populated by using SCRIPT LOAD.
// It never calls SHA-1 in Go; Redis computes and returns the digest.
func ( *Script) ( context.Context,  Scripter) error {
	// Fast path: read lock, return if hash is already set.
	.mu.RLock()
	if .hash != "" {
		.mu.RUnlock()
		return nil
	}
	.mu.RUnlock()

	// Slow path: acquire write lock and load.
	.mu.Lock()
	if .hash != "" {
		.mu.Unlock()
		return nil
	}
	 := .ScriptLoad(, .src)
	if  := .Err();  != nil {
		.mu.Unlock()
		return 
	}
	.hash = .Val()
	.mu.Unlock()
	return nil
}

func ( *Script) ( context.Context,  Scripter,  []string,  ...interface{}) *Cmd {
	// Default behavior: use client-side SHA-1 computed in NewScript.
	if !.serverSHA {
		.mu.RLock()
		 := .hash
		.mu.RUnlock()
		return .EvalSha(, , , ...)
	}

	// Server-side SHA via SCRIPT LOAD + EVALSHA.
	if  := .ensureHash(, );  != nil {
		return .Eval(, , , ...)
	}

	.mu.RLock()
	 := .hash
	.mu.RUnlock()

	 := .EvalSha(, , , ...)
	if HasErrorPrefix(.Err(), "NOSCRIPT") {
		// Script cache was flushed; reload and retry once.
		if  := .ensureHash(, );  != nil {
			return .Eval(, , , ...)
		}
		.mu.RLock()
		 = .hash
		.mu.RUnlock()
		return .EvalSha(, , , ...)
	}

	return 
}

func ( *Script) ( context.Context,  Scripter,  []string,  ...interface{}) *Cmd {
	if !.serverSHA {
		.mu.RLock()
		 := .hash
		.mu.RUnlock()
		return .EvalShaRO(, , , ...)
	}

	if  := .ensureHash(, );  != nil {
		return .EvalRO(, , , ...)
	}

	.mu.RLock()
	 := .hash
	.mu.RUnlock()

	 := .EvalShaRO(, , , ...)
	if HasErrorPrefix(.Err(), "NOSCRIPT") {
		if  := .ensureHash(, );  != nil {
			return .EvalRO(, , , ...)
		}
		.mu.RLock()
		 = .hash
		.mu.RUnlock()
		return .EvalShaRO(, , , ...)
	}

	return 
}

// Run optimistically uses EVALSHA to run the script. If script does not exist
// it is retried using EVAL.
func ( *Script) ( context.Context,  Scripter,  []string,  ...interface{}) *Cmd {
	 := .EvalSha(, , , ...)
	if isNoScriptErr(.Err()) {
		return .Eval(, , , ...)
	}
	return 
}

// RunRO optimistically uses EVALSHA_RO to run the script. If script does not exist
// it is retried using EVAL_RO.
func ( *Script) ( context.Context,  Scripter,  []string,  ...interface{}) *Cmd {
	 := .EvalShaRO(, , , ...)
	if isNoScriptErr(.Err()) {
		return .EvalRO(, , , ...)
	}
	return 
}

// isNoScriptErr reports whether err means "this digest is not cached", whether
// it arrived already normalized to ErrNoScript or as the server's raw NOSCRIPT
// error. Both are accepted because the Eval wrappers only normalize when the
// result is readable without blocking — on the deferred autopipeline face the
// raw error reaches here untouched (see cmdable.eval).
func isNoScriptErr( error) bool {
	if  == nil {
		return false
	}
	return errors.Is(, ErrNoScript) || HasErrorPrefix(, "NOSCRIPT")
}