package main

import (
	"encoding/json"
	"expvar"
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"easyaudioencode/internal/app"
	"easyaudioencode/internal/conf"

	"git.lnton.com/lnton/pkg/system"
)

var (
	buildVersion = "0.0.1" // 构建版本号
	gitBranch    = "dev"   // git 分支
	gitHash      = "debug" // git 提交点哈希值
	release      string    // 发布模式 true/false
	buildTime    string    // 构建时间戳
)

// 自定义配置目录
var configDir = flag.String("conf", "./configs", "config directory, eg: -conf /configs/")

// 默认使用随机端口
// 可使用-http-port指定端口
// 可医用-http-port = -1 使用配置文件的端口
var httpPort = flag.Int("http-port", 0, "HTTP server port; 0 uses random")

func getBuildRelease() bool {
	v, _ := strconv.ParseBool(release)
	return v
}

func main() {
	flag.Parse()

	// 初始化配置
	var bc conf.Bootstrap
	fileDir, _ := system.Abs(*configDir)
	_ = os.MkdirAll(fileDir, 0o755)
	filePath := filepath.Join(fileDir, "config.toml")
	configIsNotExistWrite(filePath)
	if err := conf.SetupConfig(&bc, filePath); err != nil {
		panic(err)
	}
	LoadEnvConfig(&bc)

	// 根据启动参数设置端口
	if *httpPort >= 0 {
		bc.Server.HTTP.Port = *httpPort
	}
	bc.Debug = !getBuildRelease()
	bc.BuildVersion = buildVersion
	bc.ConfigDir = fileDir
	bc.ConfigPath = filePath

	{
		expvar.NewString("version").Set(buildVersion)
		expvar.NewString("git_branch").Set(gitBranch)
		expvar.NewString("git_hash").Set(gitHash)
		expvar.NewString("build_time").Set(buildTime)
		expvar.Publish("timestamp", expvar.Func(func() any {
			return time.Now().Format(time.DateTime)
		}))
	}

	app.Run(&bc)
}

// configIsNotExistWrite 配置文件不存在时，回写配置
func configIsNotExistWrite(path string) {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		if err := conf.WriteConfig(conf.DefaultConfig(), path); err != nil {
			system.ErrPrintf("WriteConfig", "err", err)
		}
	}
}

type EnvPlugin struct {
	HostGrpcPort        int `json:"host_grpc_port"`
	EasyAudioEncodePort int `json:"easy_audio_encode_port"`
}

func LoadEnvConfig(bc *conf.Bootstrap) {
	easygbsAPI := os.Getenv("EASYGBS_API")
	fmt.Printf("环境变量EASYGBS_API='%s'", easygbsAPI)
	if easygbsAPI != "" {
		bc.Plugin.HttpAPI = easygbsAPI
	}

	pluginConfigs := os.Getenv("PLUGIN_CONFIGS")
	cp := EnvPlugin{}
	if err := json.Unmarshal([]byte(pluginConfigs), &cp); err != nil {
		return
	}
	fmt.Printf("环境变量PLUGIN_CONFIGS='%s'", pluginConfigs)

	// 将环境变量的值更新到全局
	if cp.HostGrpcPort > 0 {
		bc.Plugin.GrpcPort = cp.HostGrpcPort
	}
	if cp.EasyAudioEncodePort > 0 {
		bc.Server.HTTP.Port = cp.EasyAudioEncodePort
	}
}
