package docker

import (
	"github.com/docker/docker/client"
	"github.com/gofiber/fiber/v2/log"

	"gitee.ltd/lxh/wechat-robot/internal/config"
)

var (
	dockerClient *client.Client
)

// InitClient 初始化Docker客户端
func InitClient() {
	var err error
	defer func() {
		if err != nil {
			log.Panicf("Docker客户端初始化失败: %v", err)
		}
	}()

	options := []client.Opt{
		client.WithAPIVersionNegotiation(),
	}

	// 如果指定了Docker主机地址
	if config.Scd.Docker.Host != "" {
		options = append(options, client.WithHost(config.Scd.Docker.Host))
	}

	// 如果指定了API版本
	if config.Scd.Docker.APIVersion != "" {
		options = append(options, client.WithVersion(config.Scd.Docker.APIVersion))
	}

	// 创建Docker客户端
	dockerClient, err = client.NewClientWithOpts(options...)
}

// GetClient 获取Docker客户端实例
func GetClient() *client.Client {
	if dockerClient == nil {
		panic("Docker客户端未初始化，先调用InitClient")
	}
	return dockerClient
}

// CloseClient 关闭Docker客户端
func CloseClient() error {
	if dockerClient != nil {
		return dockerClient.Close()
	}
	return nil
}
