/*
Copyright © 2024 慕枫Go <mapleafgo@163.com>
*/
package main

import (
	"context"
	"errors"
	"fmt"
	"game-driver/config"
	"game-driver/config/game"
	"game-driver/config/wait"
	"game-driver/internal"
	"io/fs"
	"log"
	"os"

	"github.com/spf13/viper"
	"github.com/urfave/cli/v3"
)

// 版本信息，编译时通过 ldflags 注入
var (
	Version = "dev"
	Commit  = "unknown"
)

// formatVersion 格式化版本信息
func formatVersion() string {
	if Commit == "unknown" {
		return Version
	}
	if len(Commit) > 7 {
		return Version + " (" + Commit[:7] + ")"
	}
	return Version + " (" + Commit + ")"
}

// initConfig 读取配置文件和环境变量
func initConfig(cfgFile string) error {
	viper.SetConfigFile(cfgFile)
	viper.AutomaticEnv()

	// 读取配置文件
	if err := viper.ReadInConfig(); err == nil {
		log.Printf("使用配置文件: %s", viper.ConfigFileUsed())
	} else if errors.Is(err, fs.ErrNotExist) {
		return fmt.Errorf("配置文件不存在: %s", cfgFile)
	} else {
		return fmt.Errorf("读取配置文件错误: %w", err)
	}

	// 解析主配置
	if err := viper.Unmarshal(&config.C); err != nil {
		return fmt.Errorf("解析主配置失败: %w", err)
	}

	// 解析游戏配置
	if game.C = game.NewConfig(config.C.Point); game.C != nil {
		if err := viper.UnmarshalKey("game", &game.C); err != nil {
			return fmt.Errorf("解析游戏配置失败: %w", err)
		}
	}

	// 解析待机配置
	if wait.C = wait.NewConfig(config.C.Point); wait.C != nil {
		if err := viper.UnmarshalKey("wait", &wait.C); err != nil {
			return fmt.Errorf("解析待机配置失败: %w", err)
		}
	}

	return nil
}

func main() {
	app := &cli.Command{
		Name:    "game-driver",
		Usage:   "游戏驱动程序",
		Version: formatVersion(),
		Flags: []cli.Flag{
			&cli.StringFlag{
				Name:    "config",
				Aliases: []string{"c"},
				Value:   "config.yml",
				Usage:   "配置文件路径",
				Sources: cli.EnvVars("CONFIG_FILE"),
			},
		},
		Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
			return ctx, initConfig(cmd.String("config"))
		},
		Action: func(ctx context.Context, cmd *cli.Command) error {
			internal.Run()
			return nil
		},
	}

	if err := app.Run(context.Background(), os.Args); err != nil {
		os.Exit(1)
	}
}
