// Package version holds build-time version information for the agentteam binary.
// These variables are injected via -ldflags at build time.
package version

import (
	"runtime/debug"
	"strings"
)

const unknownVersion = "unknown"

var (
	// Version is the application version string injected from the build source.
	// Overridden at build time with -X github.com/tidbcloud/AgentTeam/desktop/internal/version.Version=...
	Version = unknownVersion

	// Commit is the git commit hash of the source tree used for the build.
	// Overridden at build time with -X github.com/tidbcloud/AgentTeam/desktop/internal/version.Commit=...
	Commit = "none"

	// BuildAt is the UTC timestamp when the binary was built.
	// Overridden at build time with -X github.com/tidbcloud/AgentTeam/desktop/internal/version.BuildAt=...
	BuildAt = "unknown"

	// GoVersion is the Go toolchain version used for compilation.
	// Overridden at build time with -X github.com/tidbcloud/AgentTeam/desktop/internal/version.GoVersion=...
	GoVersion = "unknown"
)

// BuildVersion returns the version embedded in this binary.
func BuildVersion() string {
	version := strings.TrimSpace(Version)
	if version == "" {
		return unknownVersion
	}
	return version
}

// KnownBuildVersion returns the embedded build version only when the binary was
// built with version metadata.
func KnownBuildVersion() string {
	version := BuildVersion()
	if strings.EqualFold(version, unknownVersion) || strings.EqualFold(version, "none") {
		return ""
	}
	return version
}

// KnownCommit returns the embedded commit only when build metadata supplied a
// real revision.
func KnownCommit() string {
	commit := strings.TrimSpace(Commit)
	if strings.EqualFold(commit, unknownVersion) || strings.EqualFold(commit, "none") {
		return ""
	}
	return commit
}

// DaemonWireVersion is the version value sent to the AgentTeam server in ready
// messages. Unknown local builds do not send a synthetic first-party version.
func DaemonWireVersion() string {
	version := KnownBuildVersion()
	if version == "" {
		return ""
	}
	return "agentteam/" + version
}

// GoToolchainVersion returns the Go toolchain version used to build this binary.
//
// Some release paths may forget to inject GoVersion via -ldflags. In that case,
// fall back to Go's embedded build info so version output still reports the
// actual compiler version instead of "unknown".
func GoToolchainVersion() string {
	if GoVersion != "" && GoVersion != "unknown" {
		return GoVersion
	}

	if info, ok := debug.ReadBuildInfo(); ok && info.GoVersion != "" {
		return info.GoVersion
	}

	if GoVersion != "" {
		return GoVersion
	}
	return "unknown"
}
