// Copyright (c) 2026 Alibaba Group and its affiliates

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sdk

import (
	"fmt"
	"runtime"
	"runtime/debug"
	"sync"
)

const SDKProduct = "cmaas-go-sdk"

// SDKVersion is the released version represented by the current source tree.
const SDKVersion = "v0.1.1"

var (
	resolvedVersionOnce sync.Once
	resolvedVersion     string
)

func resolveVersion() string {
	resolvedVersionOnce.Do(func() {
		resolvedVersion = SDKVersion
		info, ok := debug.ReadBuildInfo()
		if !ok {
			return
		}
		var revision string
		var modified bool
		for _, s := range info.Settings {
			switch s.Key {
			case "vcs.revision":
				revision = s.Value
			case "vcs.modified":
				modified = s.Value == "true"
			}
		}
		if revision == "" {
			return
		}
		if len(revision) > 7 {
			revision = revision[:7]
		}
		if modified {
			revision += ".dirty"
		}
		resolvedVersion = SDKVersion + "+" + revision
	})
	return resolvedVersion
}

func sdkUserAgent() string {
	return fmt.Sprintf("%s/%s (%s; %s/%s)",
		SDKProduct, resolveVersion(), runtime.Compiler, runtime.GOOS, runtime.GOARCH)
}

func sdkHeaderAttributes() map[string]interface{} {
	return map[string]interface{}{
		"user_agent": sdkUserAgent(),
	}
}
