package agent

import (
	"log/slog"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/tidbcloud/AgentTeam/desktop/internal/agent/drivercontract"
)

const (
	// proactiveIdleCompactionDefaultThreshold is the active-context token count
	// at which a capable runtime starts same-session compaction after a
	// quiescent turn. Set AGENTTEAM_PROACTIVE_COMPACTION_TOKENS to 0 to disable it.
	proactiveIdleCompactionDefaultThreshold uint64 = 150000
	// proactiveIdleCompactionCooldown prevents AgentTeam from immediately following
	// a runtime-native compaction with another manual compaction.
	proactiveIdleCompactionCooldown = 2 * time.Minute
)

func resolveProactiveIdleCompactionThreshold(cfg drivercontract.LaunchConfig) uint64 {
	raw := ""
	if cfg.Env != nil {
		raw = strings.TrimSpace(cfg.Env["AGENTTEAM_PROACTIVE_COMPACTION_TOKENS"])
	}
	if raw == "" {
		raw = strings.TrimSpace(os.Getenv("AGENTTEAM_PROACTIVE_COMPACTION_TOKENS"))
	}
	if raw == "" {
		return proactiveIdleCompactionDefaultThreshold
	}
	parsed, err := strconv.ParseUint(raw, 10, 64)
	if err != nil {
		slog.Warn("proactive idle compaction threshold is not a valid uint, using default",
			"value", raw, "default", proactiveIdleCompactionDefaultThreshold)
		return proactiveIdleCompactionDefaultThreshold
	}
	return parsed
}
