// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

package handlers

import (
	"strings"
	"time"

	"go.mau.fi/whatsmeow/types"
)

const maxDebounceWait = 12 * time.Second

func adaptiveDebounceDelay(text string) time.Duration {
	text = strings.TrimSpace(text)
	if strings.HasSuffix(text, "?") || strings.HasSuffix(text, "？") || isRepeatOrderConfirmation(text) {
		return 1500 * time.Millisecond
	}
	if len(strings.Fields(text)) >= 10 || strings.HasSuffix(text, ".") || strings.HasSuffix(text, "!") {
		return 2 * time.Second
	}
	if len(strings.Fields(text)) <= 3 {
		return 5 * time.Second
	}
	return 3 * time.Second
}

// Typing extends a burst only briefly. A missing "paused" event cannot keep it
// open forever, and even continuously refreshed composing has a hard deadline.
func pendingTextDeadline(p *pendingText, now time.Time) time.Time {
	due := p.dueAt
	if p.composingUntil.After(now) && due.Before(now.Add(3*time.Second)) {
		due = now.Add(3 * time.Second)
		if due.After(p.composingUntil) {
			due = p.composingUntil
		}
	}
	if limit := p.firstAt.Add(maxDebounceWait); due.After(limit) {
		due = limit
	}
	return due
}

// Caller holds debounceMu. Generation + pointer checks stop an expired old
// timer from draining a new burst after Stop races with its callback.
func schedulePendingTextLocked(agentID uint, sender types.JID, p *pendingText) {
	if p.timer != nil {
		p.timer.Stop()
	}
	p.generation++
	generation := p.generation
	key := debounceKey(agentID, sender)
	due := pendingTextDeadline(p, time.Now())
	p.timer = time.AfterFunc(time.Until(due), func() {
		debounceMu.Lock()
		if pending[key] != p || p.generation != generation {
			debounceMu.Unlock()
			return
		}
		if pendingTextDeadline(p, time.Now()).After(time.Now()) {
			schedulePendingTextLocked(agentID, sender, p)
			debounceMu.Unlock()
			return
		}
		delete(pending, key)
		debounceMu.Unlock()
		processPendingText(agentID, sender, p)
	})
}

func updatePendingChatPresence(agentID uint, sender string, active bool) {
	jid := types.NewJID(sender, types.DefaultUserServer)
	debounceMu.Lock()
	defer debounceMu.Unlock()
	if p := pending[debounceKey(agentID, jid)]; p != nil {
		p.composingUntil = time.Time{}
		if active {
			p.composingUntil = time.Now().Add(6 * time.Second)
		}
		schedulePendingTextLocked(agentID, jid, p)
	}
}
