package server

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

var ServerPruneCommand = &cobra.Command{
	Use:     "prune <server> [flags]",
	Aliases: []string{"p"},
	Short:   "Prune resources on a server",
	Long: `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.Infof("containers pruned: %d; space reclaimed: %s", len(cr.ContainersDeleted), cntSpaceReclaimed)

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

		log.Infof("networks pruned: %d", len(nr.NetworksDeleted))

		pruneFilters := filters.NewArgs()
		if allFilter {
			log.Debugf("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.Infof("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.Infof("volumes pruned: %d; space reclaimed: %s", len(vr.VolumesDeleted), volSpaceReclaimed)
		}

		return
	},
}

var (
	allFilter     bool
	volumesFilter bool
)

func init() {
	ServerPruneCommand.Flags().BoolVarP(
		&allFilter,
		"all",
		"a",
		false,
		"remove all unused images",
	)

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