// Package version provides version information and management for DanceLessonsCoach
package version

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

// Version information - updated during build or from VERSION file
var (
	Version   = "1.0.0"           // Semantic version (MAJOR.MINOR.PATCH)
	Commit    = ""                // Git commit hash
	Date      = ""                // Build date
	GoVersion = runtime.Version() // Go version used to build
)

// init reads version from VERSION file if ldflags not used
func init() {
	// Only read from VERSION file if Version is still default value
	// This allows ldflags to override during build
	if Version == "1.0.0" && Commit == "" && Date == "" {
		readVersionFromFile()
	}
}

// readVersionFromFile reads version info from VERSION file
func readVersionFromFile() {
	data, err := os.ReadFile("VERSION")
	if err != nil {
		// File not found or can't read - keep default values
		return
	}

	lines := strings.Split(string(data), "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "MAJOR=") {
			Version = strings.TrimPrefix(line, "MAJOR=")
		} else if strings.HasPrefix(line, "MINOR=") {
			// Append minor to version
			minor := strings.TrimPrefix(line, "MINOR=")
			if Version != "1.0.0" {
				Version = Version + "." + minor
			}
		} else if strings.HasPrefix(line, "PATCH=") {
			// Append patch to version
			patch := strings.TrimPrefix(line, "PATCH=")
			if Version != "1.0.0" {
				Version = Version + "." + patch
			}
		} else if strings.HasPrefix(line, "PRERELEASE=") {
			pre := strings.TrimPrefix(line, "PRERELEASE=")
			pre = strings.Trim(pre, `"`)
			if pre != "" && Version != "1.0.0" {
				Version = Version + "-" + pre
			}
		}
	}

	// Try to get git commit when running in development (go run)
	if Commit == "" {
		getGitCommit()
	}

	// Try to get build date when running in development (go run)
	if Date == "" {
		getBuildDate()
	}
}

// getGitCommit tries to get the current git commit hash
func getGitCommit() {
	cmd := exec.Command("git", "rev-parse", "--short", "HEAD")
	output, err := cmd.Output()
	if err == nil {
		Commit = strings.TrimSpace(string(output))
	}
}

// getBuildDate tries to get the current build date
func getBuildDate() {
	cmd := exec.Command("date", "-u", "+%Y-%m-%dT%H:%M:%SZ")
	output, err := cmd.Output()
	if err == nil {
		Date = strings.TrimSpace(string(output))
	}
}

// Info returns formatted version information
func Info() string {
	return fmt.Sprintf("DanceLessonsCoach %s (commit: %s, built: %s UTC, go: %s)", Version, Commit, Date, GoVersion)
}

// Short returns just the version number
func Short() string {
	return Version
}

// Full returns detailed version information
func Full() string {
	return fmt.Sprintf(`DanceLessonsCoach Version Information:
  Version:   %s
  Commit:    %s
  Built:     %s (UTC)
  Go:        %s`,
		Version, Commit, Date, GoVersion)
}
