package cmd

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

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

func makeLonghorn() *cobra.Command {
	const (
		valuesContent = `# 设置 Longhorn 数据存储路径
defaultSettings:
  defaultDataPath: "/data/longhorn"
# 设置默认副本数
persistence:
  reclaimPolicy: Retain
  defaultClassReplicaCount: %d 
`
	)
	var (
		replicaCount int
	)

	_cmd := &cobra.Command{
		Use:   "longhorn",
		Short: "Build Longhorn resources",
		Long:  `Build and prepare Longhorn storage resources.`,
		PreRunE: func(cmd *cobra.Command, args []string) error {
			return os.MkdirAll(filepath.Join(opt.Cfg.Make.Dir, "dependency", "longhorn"), 0755)
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			var (
				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)

			logger.Info("正在下载 Longhorn chart...")

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

			logger.Info("✅ 成功下载 Longhorn chart")

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

			logger.Info("✅ 成功创建 values.yaml")
			logger.Debug("Longhorn 资源准备完成")

			return nil
		},
	}

	_cmd.Flags().IntVar(&replicaCount, "replica-count", 2, "存储副本数")

	return _cmd
}
