package profile

import (
	"os"
	"strings"

	"github.com/tidbcloud/AgentTeam/desktop/internal/agent/runtimeconfig"
	"github.com/tidbcloud/AgentTeam/desktop/internal/provider"
)

func resolveProviderEnvKeyForRuntime(p provider.Provider) provider.Provider {
	if strings.TrimSpace(p.APIKey) != "" || strings.TrimSpace(p.EnvKey) == "" {
		return p
	}
	if value, ok := runtimeconfig.RuntimeEnvValue(strings.TrimSpace(p.EnvKey)); ok {
		p.APIKey = strings.TrimSpace(value)
	}
	return p
}

func runtimeEnvValue(key string) string {
	value, _ := runtimeconfig.RuntimeEnvValue(strings.TrimSpace(key))
	return strings.TrimSpace(value)
}

// ExpandRuntimeEnv expands $VAR and ${VAR} references using the daemon
// environment first, then the shell environment snapshot imported at startup.
func ExpandRuntimeEnv(value string) string {
	return os.Expand(value, func(key string) string {
		return runtimeEnvValue(key)
	})
}
