package server

import (
	"strings"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/i18n"
	"coopcloud.tech/abra/pkg/log"
	"github.com/docker/docker/api/types/filters"
	"github.com/spf13/cobra"
)

// translators: `abra server prune` aliases. use a comma separated list of
// aliases with no spaces in between
var serverPruneliases = i18n.G("p")

var ServerPruneCommand = &cobra.Command{
	// translators: `server prune` command
	Use:     i18n.G("prune <server> [flags]"),
	Aliases: strings.Split(serverPruneliases, ","),
	// translators: Short description for `server prune` command
	Short: i18n.G("Prune resources on a server"),
	Long: i18n.G(`Prunes unused containers, networks, and dangling images.

Use "--volumes/-v" to remove volumes that are not associated with a deployed
app. This can result in unwanted data loss if not used carefully.`),
	Args: cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.ServerNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		serverName := internal.ValidateServer(args)

		cl, err := client.New(serverName)
		if err != nil {
			log.Fatal(err)
		}

		var filterArgs filters.Args

		cr, err := cl.ContainersPrune(cmd.Context(), filterArgs)
		if err != nil {
			log.Fatal(err)
		}

		cntSpaceReclaimed := formatter.ByteCountSI(cr.SpaceReclaimed)
		log.Info(i18n.G("containers pruned: %d; space reclaimed: %s", len(cr.ContainersDeleted), cntSpaceReclaimed))

		nr, err := cl.NetworksPrune(cmd.Context(), filterArgs)
		if err != nil {
			log.Fatal(err)
		}

		log.Info(i18n.G("networks pruned: %d", len(nr.NetworksDeleted)))

		pruneFilters := filters.NewArgs()
		if allFilter {
			log.Debug(i18n.G("removing all images, not only dangling ones"))
			pruneFilters.Add("dangling", "false")
		}

		ir, err := cl.ImagesPrune(cmd.Context(), pruneFilters)
		if err != nil {
			log.Fatal(err)
		}

		imgSpaceReclaimed := formatter.ByteCountSI(ir.SpaceReclaimed)
		log.Info(i18n.G("images pruned: %d; space reclaimed: %s", len(ir.ImagesDeleted), imgSpaceReclaimed))

		if volumesFilter {
			vr, err := cl.VolumesPrune(cmd.Context(), filterArgs)
			if err != nil {
				log.Fatal(err)
			}

			volSpaceReclaimed := formatter.ByteCountSI(vr.SpaceReclaimed)
			log.Info(i18n.G("volumes pruned: %d; space reclaimed: %s", len(vr.VolumesDeleted), volSpaceReclaimed))
		}

		return
	},
}

var (
	allFilter     bool
	volumesFilter bool
)

func init() {
	ServerPruneCommand.Flags().BoolVarP(
		&allFilter,
		i18n.G("all"),
		i18n.GC("a", "server prune"),
		false,
		i18n.G("remove all unused images"),
	)

	ServerPruneCommand.Flags().BoolVarP(
		&volumesFilter,
		i18n.G("volumes"),
		i18n.G("v"),
		false,
		i18n.G("remove volumes"),
	)
}
