package config

import (
	"fmt"
	"strings"

	"hyapp/pkg/configx"
	"hyapp/pkg/logx"
)

// Config 描述 robot-service 的进程配置；机器人池只拥有账号可用性事实，不拥有用户资料和房间状态。
type Config struct {
	ServiceName    string `yaml:"service_name"`
	NodeID         string `yaml:"node_id"`
	Environment    string `yaml:"environment"`
	GRPCAddr       string `yaml:"grpc_addr"`
	HealthHTTPAddr string `yaml:"health_http_addr"`
	MySQLDSN       string `yaml:"mysql_dsn"`
	// LegacyGameDatabase 只用于首次把旧 game-service 机器人表复制到 robot-service 新表；迁移完成后读写不再访问旧表。
	LegacyGameDatabase string      `yaml:"legacy_game_database"`
	Log                logx.Config `yaml:"log"`
}

func Default() Config {
	return Config{
		ServiceName:        "robot-service",
		NodeID:             "robot-local",
		Environment:        "local",
		GRPCAddr:           ":13011",
		HealthHTTPAddr:     ":13111",
		MySQLDSN:           "hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_robot?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true",
		LegacyGameDatabase: "hyapp_game",
		Log: logx.Config{
			Level:           "info",
			Format:          "json",
			MaxPayloadBytes: 2048,
		},
	}
}

func Load(path string) (Config, error) {
	cfg := Default()
	if path != "" {
		if err := configx.LoadYAML(path, &cfg); err != nil {
			return Config{}, err
		}
	}
	if err := cfg.Normalize(); err != nil {
		return Config{}, err
	}
	return cfg, nil
}

func (cfg *Config) Normalize() error {
	cfg.ServiceName = strings.TrimSpace(cfg.ServiceName)
	if cfg.ServiceName == "" {
		cfg.ServiceName = "robot-service"
	}
	cfg.NodeID = strings.TrimSpace(cfg.NodeID)
	if cfg.NodeID == "" {
		cfg.NodeID = cfg.ServiceName
	}
	cfg.Environment = strings.TrimSpace(cfg.Environment)
	if cfg.Environment == "" {
		cfg.Environment = "local"
	}
	cfg.GRPCAddr = strings.TrimSpace(cfg.GRPCAddr)
	if cfg.GRPCAddr == "" {
		cfg.GRPCAddr = ":13011"
	}
	cfg.HealthHTTPAddr = strings.TrimSpace(cfg.HealthHTTPAddr)
	if cfg.HealthHTTPAddr == "" {
		cfg.HealthHTTPAddr = ":13111"
	}
	cfg.MySQLDSN = strings.TrimSpace(cfg.MySQLDSN)
	if cfg.MySQLDSN == "" {
		return fmt.Errorf("mysql_dsn is required")
	}
	cfg.LegacyGameDatabase = strings.TrimSpace(cfg.LegacyGameDatabase)
	return nil
}
