// Package version defines current build app information
package version

import (
	"fmt"
	"os"
	"runtime"
	"strings"
)

//go:generate go-enum -f=$GOFILE --lower --marshal

// AppName stores the Application Name
const (
	AppName            = "qfixpt"
	poweredBy          = "Powered by Quantex Technologies"
	quantexEnvironment = "QUANTEX_ENVIRONMENT"
)

var (
	// See tools/build.sh script to see how these variables are set
	versionBase = "0.1" //nolint:gochecknoglobals // Should be global cos this is set on the build with version info
	buildHash   string  //nolint:gochecknoglobals // Idem
	buildBranch string  //nolint:gochecknoglobals // Idem
	builtTime   string  //nolint:gochecknoglobals // Idem
	hostname    string  //nolint:gochecknoglobals // Idem
)

// EnvironmentType environments
// ENUM(
// prod
// open-demo
// demo
// dev
// )
type EnvironmentType int //nolint:recvcheck // The methods of this are autogenerated

var environment EnvironmentType //nolint:gochecknoglobals // Just keept this global to avoid having to create an instance

func init() {
	aux := os.Getenv(quantexEnvironment)
	if aux == "" {
		panic("QUANTEX_ENVIRONMENT is not set")
	}

	env, err := ParseEnvironmentType(aux)
	if err != nil {
		panic("Invalid QUANTEX_ENVIRONMENT value: " + aux + " " + err.Error())
	}

	environment = env
}

// Base returns the version base name
func Base() string {
	return versionBase
}

// BuildHash returns the build hash
func BuildHash() string {
	return buildHash
}

// BuildBranch returns the build branch
func BuildBranch() string {
	return buildBranch
}

// Hostname returns the build time
func Hostname() string {
	return hostname
}

// Name returns the version name
func Name() string {
	bh := buildHash
	if len(buildHash) >= 8 {
		bh = buildHash[0:8]
	}

	return versionBase + "-" + bh
}

// BuiltTime returns the build time
func BuiltTime() string {
	return builtTime
}

// Environment returns service environment
func Environment() EnvironmentType {
	return environment
}

// Environment returns service environment
func BuildFullInfo() string {
	bt := strings.Replace(builtTime, "-", " ", -1)
	bh := buildHash

	if len(buildHash) >= 8 {
		bh = buildHash[0:8]
	}

	return fmt.Sprintf("v%s-%s-%s, built on %s ", versionBase, buildBranch, bh, bt)
}

// Info returns the complete version information
func Info() string {
	sb := strings.Builder{}
	// revive:disable No need to handle errors here
	sb.WriteString(fmt.Sprintf("v%s \n", versionBase))
	sb.WriteString(fmt.Sprintln("  Build ", BuildFullInfo()))
	sb.WriteString(fmt.Sprintln(" ", poweredBy, ""))
	sb.WriteString(fmt.Sprintf("  Go %s \n", runtime.Version()))
	sb.WriteString(fmt.Sprintf("  Environment %s \n", environment))
	sb.WriteString(fmt.Sprintf("  Built from %s \n", hostname))
	// revive:enable
	return sb.String()
}
