package autocomplete

import (
	"context"
	"fmt"

	"coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/urfave/cli/v3"
)

// AppNameComplete copletes app names.
func AppNameComplete(ctx context.Context, cmd *cli.Command) {
	appNames, err := app.GetAppNames()
	if err != nil {
		log.Warn(err)
	}

	if cmd.NArg() > 0 {
		return
	}

	for _, a := range appNames {
		fmt.Println(a)
	}
}

func ServiceNameComplete(appName string) {
	serviceNames, err := app.GetAppServiceNames(appName)
	if err != nil {
		return
	}
	for _, s := range serviceNames {
		fmt.Println(s)
	}
}

// RecipeNameComplete completes recipe names.
func RecipeNameComplete(ctx context.Context, cmd *cli.Command) {
	catl, err := recipe.ReadRecipeCatalogue(false)
	if err != nil {
		log.Warn(err)
	}

	if cmd.NArg() > 0 {
		return
	}

	for name := range catl {
		fmt.Println(name)
	}
}

// RecipeVersionComplete completes versions for the recipe.
func RecipeVersionComplete(recipeName string) {
	catl, err := recipe.ReadRecipeCatalogue(false)
	if err != nil {
		log.Warn(err)
	}

	for _, v := range catl[recipeName].Versions {
		for v2 := range v {
			fmt.Println(v2)
		}
	}
}

// ServerNameComplete completes server names.
func ServerNameComplete(ctx context.Context, cmd *cli.Command) {
	files, err := app.LoadAppFiles("")
	if err != nil {
		log.Fatal(err)
	}

	if cmd.NArg() > 0 {
		return
	}

	for _, appFile := range files {
		fmt.Println(appFile.Server)
	}
}

// SubcommandComplete completes sub-commands.
func SubcommandComplete(ctx context.Context, cmd *cli.Command) {
	if cmd.NArg() > 0 {
		return
	}

	subcmds := []string{
		"app",
		"autocomplete",
		"catalogue",
		"recipe",
		"server",
		"upgrade",
	}

	for _, cmd := range subcmds {
		fmt.Println(cmd)
	}
}
