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 makeRedis() *cobra.Command {
	const (
		valuesTemplate = `# Redis configuration
architecture: replication

image:
  registry: docker.io
  repository: bitnami/redis
  tag: 8.2.2
  pullPolicy: IfNotPresent

auth:
  enabled: true
  password: "%s"

master:
  persistence:
    enabled: true
    storageClass: "longhorn"
    size: 5Gi
# resources:
#   requests:
#     memory: "512Mi"
#     cpu: "250m"
#   limits:
#     memory: "1Gi"
#     cpu: "500m"

replica:
  replicaCount: %d
  persistence:
    enabled: true
    storageClass: "longhorn"
    size: 5Gi
# resources:
#   requests:
#     memory: "512Mi"
#     cpu: "250m"
#   limits:
#     memory: "1Gi"
#     cpu: "500m"

metrics:
  enabled: false
  serviceMonitor:
    enabled: false
`
		defaultPassword = "HybridScope0xRed1s."
	)

	var (
		replicas int
		password string
	)

	_cmd := &cobra.Command{
		Use:   "redis",
		Short: "Build Redis resources",
		Long:  `Build and prepare Redis cache resources.`,
		PreRunE: func(cmd *cobra.Command, args []string) error {
			return os.MkdirAll(filepath.Join(opt.Cfg.Make.Dir, "dependency", "redis"), 0755)
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			var (
				chartURL   = "https://artifactory.yizhisec.com:443/artifactory/filestore/hsv3/charts/redis-23.2.2.tgz"
				redisDir   = filepath.Join(opt.Cfg.Make.Dir, "dependency", "redis")
				chartFile  = filepath.Join(redisDir, "redis-23.2.2.tgz")
				valuesFile = filepath.Join(redisDir, "values.yaml")
			)

			if password == "******" {
				password = defaultPassword
			}

			logger.Info("开始构建 Redis 资源...")
			logger.Debug("下载地址: %s", chartURL)
			logger.Debug("目标目录: %s", redisDir)
			logger.Debug("Redis 副本数: %d", replicas)

			// Download Redis chart
			logger.Info("正在下载 Redis chart...")
			if err := downloader.Download(
				cmd.Context(),
				chartURL,
				chartFile,
				downloader.WithInsecureSkipVerify(),
			); err != nil {
				logger.Info("❌ 下载 Redis chart 失败")
				return err
			}
			logger.Info("✅ 成功下载 Redis chart")

			// Generate values.yaml
			logger.Debug("创建 values.yaml: %s", valuesFile)
			valuesContent := fmt.Sprintf(valuesTemplate, password, replicas)
			if err := os.WriteFile(valuesFile, []byte(valuesContent), 0644); err != nil {
				logger.Debug("创建 values.yaml 失败: %v", err)
				logger.Info("❌ 创建 values.yaml 失败")
				return err
			}
			logger.Info("✅ 成功创建 values.yaml")

			logger.Info("✅ Redis 资源构建成功")
			logger.Debug("Redis 资源准备完成")

			return nil
		},
	}

	_cmd.Flags().IntVar(&replicas, "replica-count", 2, "Redis 副本数")
	_cmd.Flags().StringVar(&password, "password", "******", "Redis 密码")

	return _cmd
}
