package maker

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

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

type RedisOpt func(*redisOpt)

type redisOpt struct {
	ReplicaCount int
	Password     string
	Storage      string
}

func WithRedisReplicaCount(replica int) RedisOpt {
	return func(o *redisOpt) {
		if replica > 0 {
			o.ReplicaCount = replica
		}
	}
}

func WithRedisPassword(password string) RedisOpt {
	return func(o *redisOpt) {
		if password != "" {
			o.Password = password
		}
	}
}

func WithRedisStorage(storage string) RedisOpt {
	return func(o *redisOpt) {
		if matched, _ := regexp.MatchString(`^\d+(\.\d+)?[EPTGMK]i?$`, storage); matched {
			o.Storage = storage
		}
	}
}

func (m *maker) Redis(ctx context.Context, opts ...RedisOpt) error {
	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: %s

replica:
  replicaCount: %d
  persistence:
    enabled: true
    storageClass: "longhorn"
    size: %s

metrics:
  enabled: false
  serviceMonitor:
    enabled: false
`
		defaultPassword = "HybridScope0xRed1s."
		chartURL        = "https://artifactory.yizhisec.com:443/artifactory/filestore/hsv3/charts/redis-23.2.2.tgz"
		chartFilename   = "redis-23.2.2.tgz"
	)

	o := &redisOpt{
		ReplicaCount: 2,
		Password:     "HybridScope0xRed1s.",
		Storage:      "5Gi",
	}
	for _, fn := range opts {
		fn(o)
	}

	redisDir := filepath.Join(opt.Cfg.Make.Dir, "dependency", "redis")
	chartFile := filepath.Join(redisDir, chartFilename)
	valuesFile := filepath.Join(redisDir, "values.yaml")

	if err := os.MkdirAll(redisDir, 0755); err != nil {
		return err
	}

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

	if err := downloader.Download(
		ctx,
		chartURL,
		chartFile,
		downloader.WithInsecureSkipVerify(),
	); err != nil {
		logger.Debug("❌ 下载 Redis chart 失败")
		return err
	}
	logger.Debug("✅ 成功下载 Redis chart")

	bs := fmt.Sprintf(valuesTemplate, o.Password, o.Storage, o.ReplicaCount, o.Storage)
	if err := os.WriteFile(valuesFile, []byte(bs), 0644); err != nil {
		logger.Info("❌ 创建 values.yaml 失败")
		return err
	}
	logger.Debug("✅ 成功创建 values.yaml")

	logger.Info("✅ Redis 资源构建成功")

	return nil
}
