package recipe

import (
	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/spf13/cobra"
)

var RecipeFetchCommand = &cobra.Command{
	Use:     "fetch [recipe | --all] [flags]",
	Aliases: []string{"f"},
	Short:   "Clone recipe(s) locally",
	Args:    cobra.RangeArgs(0, 1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.RecipeNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		var recipeName string
		if len(args) > 0 {
			recipeName = args[0]
		}

		if recipeName == "" && !fetchAllRecipes {
			log.Fatal("missing [recipe] or --all/-a")
		}

		if recipeName != "" && fetchAllRecipes {
			log.Fatal("cannot use [recipe] and --all/-a together")
		}

		ensureCtx := internal.GetEnsureContext()
		if recipeName != "" {
			r := internal.ValidateRecipe(args, cmd.Name())
			if err := r.Ensure(ensureCtx); err != nil {
				log.Fatal(err)
			}
			return
		}

		catalogue, err := recipe.ReadRecipeCatalogue(internal.Offline)
		if err != nil {
			log.Fatal(err)
		}

		catlBar := formatter.CreateProgressbar(len(catalogue), "fetching latest recipes...")
		for recipeName := range catalogue {
			r := recipe.Get(recipeName)
			if err := r.Ensure(ensureCtx); err != nil {
				log.Error(err)
			}
			catlBar.Add(1)
		}
	},
}

var (
	fetchAllRecipes bool
)

func init() {
	RecipeFetchCommand.Flags().BoolVarP(
		&fetchAllRecipes,
		"all",
		"a",
		false,
		"fetch all recipes",
	)
}
