package maker

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"gitea.loveuer.com/yizhisec/pkg3/logger"
	"yizhisec.com/hsv2/forge/internal/opt"
	"yizhisec.com/hsv2/forge/pkg/downloader"
)

func (m *maker) Longhorn(ctx context.Context, replica int) error {
	const (
		valuesContent = `# 设置 Longhorn 数据存储路径
defaultSettings:
  defaultDataPath: "/data/longhorn"
# 设置默认副本数
persistence:
  reclaimPolicy: Retain
  defaultClassReplicaCount: %d 
`
	)

	var (
		err         error
		chartURL    = "https://artifactory.yizhisec.com:443/artifactory/filestore/hsv3/charts/longhorn-1.10.0.tgz"
		longhornDir = filepath.Join(opt.Cfg.Make.Dir, "dependency", "longhorn")
		chartFile   = filepath.Join(longhornDir, "longhorn-1.10.0.tgz")
		valuesFile  = filepath.Join(longhornDir, "values.yaml")
	)

	logger.Info("☑️ 开始准备 Longhorn 资源...")
	logger.Debug("下载地址: %s", chartURL)
	logger.Debug("目标目录: %s", longhornDir)

	if err = os.MkdirAll(filepath.Join(opt.Cfg.Make.Dir, "dependency", "longhorn"), 0755); err != nil {
		return err
	}

	// Download the chart file
	if err = downloader.Download(
		ctx,
		chartURL,
		chartFile,
		downloader.WithInsecureSkipVerify(),
	); err != nil {
		logger.Info("❌ 下载 Longhorn chart 失败")
		return err
	}

	// Create values.yaml file
	bs := []byte(fmt.Sprintf(valuesContent, replica))
	if err := os.WriteFile(valuesFile, bs, 0644); err != nil {
		logger.Debug("创建 values.yaml 失败: %v", err)
		logger.Info("❌ 创建 values.yaml 失败")
		return err
	}

	logger.Info("✅ 成功创建 longhorn 资源!!!")

	return nil
}
