package config

import (
	"fmt"
	"strings"
	"time"

	"github.com/spf13/viper"
)

// Config 应用所有配置的集合
type Config struct {
	Database      DatabaseConfig
	Server        ServerConfig
	Log           LogConfig
	Redis         RedisConfig      `mapstructure:"redis"`
	SessionSecret string           `mapstructure:"session_secret"`
	EncryptionKey string           `mapstructure:"encryption_key"`
	Repository    RepositoryConfig `mapstructure:"repository"`
}

// DatabaseConfig 存储数据库连接信息
type DatabaseConfig struct {
	DSN             string        `mapstructure:"dsn"`
	MaxIdleConns    int           `mapstructure:"max_idle_conns"`
	MaxOpenConns    int           `mapstructure:"max_open_conns"`
	ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
}

// ServerConfig 存储HTTP服务器配置
type ServerConfig struct {
	Port        string   `mapstructure:"port"`
	Host        string   `yaml:"host"`
	CORSOrigins []string `yaml:"cors_origins"`
}

// LogConfig 存储日志配置
type LogConfig struct {
	Level      string `mapstructure:"level"       json:"level"`
	Format     string `mapstructure:"format"      json:"format"`
	EnableFile bool   `mapstructure:"enable_file" json:"enable_file"`
	FilePath   string `mapstructure:"file_path"   json:"file_path"`

	// 日志轮转配置（可选）
	MaxSize    int  `yaml:"max_size"`    // MB，默认 100
	MaxBackups int  `yaml:"max_backups"` // 默认 7
	MaxAge     int  `yaml:"max_age"`     // 天，默认 30
	Compress   bool `yaml:"compress"`    // 默认 true
}

type RedisConfig struct {
	DSN string `mapstructure:"dsn"`
}

type RepositoryConfig struct {
	BasePoolTTLMinutes int `mapstructure:"base_pool_ttl_minutes"`
	BasePoolTTIMinutes int `mapstructure:"base_pool_tti_minutes"`
}

// LoadConfig 从文件和环境变量加载配置
func LoadConfig() (*Config, error) {
	// 设置配置文件名和路径
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	viper.AddConfigPath("/etc/gemini-balancer/") // for production
	// 允许从环境变量读取
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	viper.AutomaticEnv()

	// 设置默认值
	viper.SetDefault("server.port", "9000")
	viper.SetDefault("log.level", "info")
	viper.SetDefault("log.format", "text")
	viper.SetDefault("log.enable_file", false)
	viper.SetDefault("log.file_path", "logs/gemini-balancer.log")
	viper.SetDefault("database.type", "sqlite")
	viper.SetDefault("database.dsn", "gemini-balancer.db")
	viper.SetDefault("database.max_idle_conns", 10)
	viper.SetDefault("database.max_open_conns", 100)
	viper.SetDefault("database.conn_max_lifetime", "1h")
	viper.SetDefault("encryption_key", "")

	viper.SetDefault("repository.base_pool_ttl_minutes", 60)
	viper.SetDefault("repository.base_pool_tti_minutes", 10)

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
			return nil, fmt.Errorf("error reading config file: %w", err)
		}
	}
	var cfg Config
	if err := viper.Unmarshal(&cfg); err != nil {
		return nil, fmt.Errorf("unable to decode config into struct: %w", err)
	}
	return &cfg, nil
}
