package recipe

import (
	"context"

	"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/urfave/cli/v3"
)

var recipeFetchCommand = cli.Command{
	Name:          "fetch",
	Usage:         "Fetch recipe(s)",
	Aliases:       []string{"f"},
	UsageText:     "abra recipe fetch [<recipe>] [options]",
	Description:   "Retrieves all recipes if no <recipe> argument is passed",
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.RecipeNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		recipeName := cmd.Args().First()
		r := recipe.Get(recipeName)
		if recipeName != "" {
			internal.ValidateRecipe(cmd)
			if err := r.Ensure(false, false); err != nil {
				log.Fatal(err)
			}
			return nil
		}

		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(false, false); err != nil {
				log.Error(err)
			}
			catlBar.Add(1)
		}

		return nil
	},
}
