package conf

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"math/rand/v2"

	"git.apinb.com/bsm-sdk/core/env"
	"git.apinb.com/bsm-sdk/core/print"
	"git.apinb.com/bsm-sdk/core/utils"
	"git.apinb.com/bsm-sdk/core/vars"
	yaml "gopkg.in/yaml.v3"
)

func New(srvKey string, cfg any) {
	env.NewEnv()

	// 设置服务键
	vars.ServiceKey = srvKey

	// 获取主机名
	vars.HostName, _ = os.Hostname()

	// 构造配置文件路径,输出配置文件信息
	cfp := fmt.Sprintf("%s_%s.yaml", strings.ToLower(srvKey), env.Runtime.Mode)
	cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)

	print.Info("[BSM - %s] Config File: %s", srvKey, cfp)
	print.Info("[BSM - %s] Check Configure ...", vars.ServiceKey)

	// 读取配置文件内容
	yamlFile, err := os.ReadFile(cfp)
	if err != nil {
		log.Fatalf("ERROR: %v", err)
	}

	// 检查配置文件中是否存在Service和Port字段
	if !strings.Contains(string(yamlFile), "Service:") {
		log.Fatalln("ERROR: Service Not Nil", cfp)
	}

	// 解析YAML
	err = yaml.Unmarshal(yamlFile, cfg)
	if err != nil {
		log.Fatalf("ERROR: %v", err)
	}
}

func NotNil(values ...string) {
	for _, value := range values {
		if strings.TrimSpace(value) == "" {
			log.Fatalln("ERROR:Must config key not nil")
		}
	}
}

func PrintInfo(ip string, port int) {
	print.Success("[BSM - %s] Config Check Success.", vars.ServiceKey)
	print.Info("[BSM - %s] Service Name: %s", vars.ServiceKey, vars.ServiceKey)
	print.Info("[BSM - %s] Runtime Mode: %s", vars.ServiceKey, env.Runtime.Mode)
	print.Info("[BSM - %s] Listen Addr: %s:%d", vars.ServiceKey, ip, port)
}

func CheckPort(port int) int {
	if port <= 0 || port >= 65535 {
		r := rand.New(rand.NewPCG(1000, uint64(time.Now().UnixNano())))
		return r.IntN(65535-1024) + 1024 // 生成1024到65535之间的随机端口
	}
	return port
}

func CheckIP(ip string) string {
	if ip == "" {
		return utils.GetLocationIP()
	}
	return ip
}