package cmd

import (
	"os"
	"path/filepath"

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

func makeBinaries() *cobra.Command {
	cmd := &cobra.Command{
		Use:     "binaries",
		Aliases: []string{"bin", "B"},
		Short:   "Build binary files",
		Long:    `Build all required binary files for the project.`,
		PreRunE: func(cmd *cobra.Command, args []string) error {
			return os.MkdirAll(filepath.Join(opt.Cfg.Make.Dir, "dependency", "bin"), 0755)
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			var (
				tarURL = "https://artifactory.yizhisec.com:443/artifactory/filestore/hsv3/k8s-bin.tar"
				binDir = filepath.Join(opt.Cfg.Make.Dir, "dependency")
			)

			logger.Info("开始准备 k8s 二进制文件...")
			logger.Debug("下载地址: %s", tarURL)
			logger.Debug("目标目录: %s", binDir)

			logger.Info("正在下载二进制文件...")

			if err := archiver.DownloadAndExtract(
				cmd.Context(),
				tarURL,
				binDir,
				archiver.WithInsecureSkipVerify(),
				archiver.WithGzipCompression(true),
			); err != nil {
				logger.Info("❌ 下载并解压二进制文件失败")
				return err
			}

			logger.Info("✅ 成功下载并解压二进制文件")
			return nil
		},
	}

	return cmd
}
