//go:generate go run .
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/uozi-tech/cosy/logger"
)

type VersionInfo struct {
	Version    string `json:"version"`
	BuildId    int    `json:"build_id"`
	TotalBuild int    `json:"total_build"`
}

func main() {
	logger.Init("release")

	_, file, _, ok := runtime.Caller(0)
	if !ok {
		logger.Error("Unable to get the current file")
		return
	}
	basePath := filepath.Join(filepath.Dir(file), "../../")

	versionFile, err := os.Open(path.Join(basePath, "app/dist/version.json"))
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			logger.Error("\"dist/version.json\" not found, load from src instead")
			versionFile, err = os.Open(path.Join(basePath, "app/src/version.json"))
		}

		if err != nil {
			logger.Fatalf("Failed to open version.json: %v", err)
			return
		}
	}

	defer versionFile.Close()

	// Read the version.json file
	data, err := io.ReadAll(versionFile)
	if err != nil {
		logger.Fatalf("Failed to read version.json: %v", err)
	}

	// Parse the JSON data
	var versionInfo VersionInfo
	err = json.Unmarshal(data, &versionInfo)
	if err != nil {
		logger.Fatalf("Failed to parse JSON: %v", err)
	}

	// get current git commit hash
	commitHash, err := getGitCommitHash(basePath)
	if err != nil {
		logger.Fatalf("Failed to get git commit hash: %v", err)
	}

	err = generateVersionGenGo(basePath, versionInfo, commitHash)
	if err != nil {
		logger.Fatalf("Failed to generate version.gen.go: %v", err)
	}
}

func getGitCommitHash(basePath string) (string, error) {
	cmd := exec.Command("git", "-C", basePath, "rev-parse", "HEAD")
	commitHash, err := cmd.Output()
	if err != nil {
		return "", err
	}

	return strings.TrimRight(string(commitHash), "\r\n"), nil
}

func generateVersionGenGo(basePath string, versionInfo VersionInfo, commitHash string) error {
	// Generate the version.gen.go file content
	genContent := fmt.Sprintf(`// Code generated by cmd/version/generate.go; DO NOT EDIT.

package version

func init() {
	Version = "%s"
	BuildId = %d
	TotalBuild = %d
	Hash = "%s"
}
`, versionInfo.Version, versionInfo.BuildId, versionInfo.TotalBuild, strings.TrimRight(commitHash, "\r\n"))

	genPath := filepath.Join(basePath, "internal/version/version.gen.go")
	err := os.WriteFile(genPath, []byte(genContent), 0644)
	if err != nil {
		return err
	}

	logger.Info("version.gen.go has been generated successfully.")
	return nil
}
