package config

import (
	"fmt"
	"strings"
	"time"

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

// Config 描述 game-service 启动所需的最小依赖。
type Config struct {
	ServiceName string `yaml:"service_name"`
	NodeID      string `yaml:"node_id"`
	Environment string `yaml:"environment"`
	GRPCAddr    string `yaml:"grpc_addr"`
	// HealthHTTPAddr 是给 CLB/发布脚本探活使用的 HTTP 监听地址，不承载业务流量。
	HealthHTTPAddr    string        `yaml:"health_http_addr"`
	MySQLDSN          string        `yaml:"mysql_dsn"`
	WalletServiceAddr string        `yaml:"wallet_service_addr"`
	UserServiceAddr   string        `yaml:"user_service_addr"`
	LaunchSessionTTL  time.Duration `yaml:"launch_session_ttl"`
	Log               logx.Config   `yaml:"log"`
}

// Default 返回本地开发默认配置。
func Default() Config {
	return Config{
		ServiceName:       "game-service",
		NodeID:            "game-local",
		Environment:       "local",
		GRPCAddr:          ":13008",
		HealthHTTPAddr:    ":13108",
		MySQLDSN:          "hyapp:hyapp@tcp(127.0.0.1:23306)/hyapp_game?parseTime=true&charset=utf8mb4&loc=UTC&multiStatements=true",
		WalletServiceAddr: "127.0.0.1:13004",
		UserServiceAddr:   "127.0.0.1:13005",
		LaunchSessionTTL:  15 * time.Minute,
		Log: logx.Config{
			Level:           "info",
			Format:          "json",
			MaxPayloadBytes: 2048,
		},
	}
}

// Load 从 YAML 文件读取配置，并填充默认值。
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
}

// Normalize 在启动时收敛配置，避免运行期才暴露关键依赖缺失。
func (cfg *Config) Normalize() error {
	cfg.ServiceName = strings.TrimSpace(cfg.ServiceName)
	if cfg.ServiceName == "" {
		cfg.ServiceName = "game-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 = ":13008"
	}
	cfg.HealthHTTPAddr = strings.TrimSpace(cfg.HealthHTTPAddr)
	if cfg.HealthHTTPAddr == "" {
		cfg.HealthHTTPAddr = ":13108"
	}
	cfg.MySQLDSN = strings.TrimSpace(cfg.MySQLDSN)
	if cfg.MySQLDSN == "" {
		return fmt.Errorf("mysql_dsn is required")
	}
	cfg.WalletServiceAddr = strings.TrimSpace(cfg.WalletServiceAddr)
	if cfg.WalletServiceAddr == "" {
		return fmt.Errorf("wallet_service_addr is required")
	}
	cfg.UserServiceAddr = strings.TrimSpace(cfg.UserServiceAddr)
	if cfg.UserServiceAddr == "" {
		return fmt.Errorf("user_service_addr is required")
	}
	if cfg.LaunchSessionTTL <= 0 {
		cfg.LaunchSessionTTL = 15 * time.Minute
	}
	return nil
}
