// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package services

import (
	"go.mau.fi/whatsmeow/types"
	"math/rand"
	"sync"
	"time"
	"unicode/utf8"
)

type automaticReplyKey struct {
	agentID uint
	id      string
}

// Remember IDs before sending, so an immediate WhatsApp echo cannot be
// mistaken for a human reply while the AI handler is still saving history.
// Persisted ChatHistory provides the fallback after restart or eviction.
var automaticReplies = struct {
	sync.Mutex
	ids   map[automaticReplyKey]bool
	order [4096]automaticReplyKey
	next  int
}{ids: make(map[automaticReplyKey]bool)}

func rememberAutomaticReply(agentID uint, id string) {
	if id == "" {
		return
	}
	key := automaticReplyKey{agentID, id}
	automaticReplies.Lock()
	defer automaticReplies.Unlock()
	if automaticReplies.ids[key] {
		return
	}
	delete(automaticReplies.ids, automaticReplies.order[automaticReplies.next])
	automaticReplies.ids[key] = true
	automaticReplies.order[automaticReplies.next] = key
	automaticReplies.next = (automaticReplies.next + 1) % len(automaticReplies.order)
}

func IsAutomaticReplyMessage(agentID uint, id string) bool {
	if id == "" {
		return false
	}
	automaticReplies.Lock()
	defer automaticReplies.Unlock()
	return automaticReplies.ids[automaticReplyKey{agentID, id}]
}

// AdaptiveAIReplyDelay counts characters rather than UTF-8 bytes. Explicit
// workflow/handoff acknowledgements can still pass zero to skip typing delay.
func AdaptiveAIReplyDelay(message string) time.Duration {
	return max(time.Second, min(4500*time.Millisecond, time.Duration(utf8.RuneCountInString(message))*25*time.Millisecond))
}

// Every part retains automatic origin and rechecks operator takeover after waiting.
func (w *waInstance) SendAutomaticReplyPartAndGetID(to types.JID, message string, delay time.Duration, beforeSend func() error) (string, error) {
	return w.sendTextWithOriginAndGetID(to, message, max(0, min(60*time.Second, delay)), true, beforeSend)
}

func (w *waInstance) SendAutomaticReplyWithDelayAndGetID(to types.JID, message string, minSeconds, maxSeconds int, beforeSend func() error) (string, error) {
	minSeconds = max(0, min(30, minSeconds))
	maxSeconds = max(minSeconds, min(30, maxSeconds))
	delay := minSeconds
	if maxSeconds > minSeconds {
		delay += rand.Intn(maxSeconds - minSeconds + 1)
	}
	return w.SendAutomaticReplyPartAndGetID(to, message, time.Duration(delay)*time.Second, beforeSend)
}
