package app

import (
	"fmt"
	"strings"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/i18n"
	"coopcloud.tech/abra/pkg/log"
	"github.com/spf13/cobra"
)

// translators: `abra app backup list` aliases. use a comma separated list of aliases with
// no spaces in between
var appBackupListAliases = i18n.G("ls")

var AppBackupListCommand = &cobra.Command{
	// translators: `app backup list` command
	Use:     i18n.G("list <domain> [flags]"),
	Aliases: strings.Split(appBackupListAliases, ","),
	// translators: Short description for `app backup list` command
	Short: i18n.G("List the contents of a snapshot"),
	Args:  cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)

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

		targetContainer, err := internal.RetrieveBackupBotContainer(cl)
		if err != nil {
			log.Fatal(err)
		}

		execEnv := []string{
			fmt.Sprintf("SERVICE=%s", app.Domain),
			"MACHINE_LOGS=true",
		}

		if snapshot != "" {
			log.Debug(i18n.G("including SNAPSHOT=%s in backupbot exec invocation", snapshot))
			execEnv = append(execEnv, fmt.Sprintf("SNAPSHOT=%s", snapshot))
		}

		if showAllPaths {
			log.Debug(i18n.G("including SHOW_ALL=%v in backupbot exec invocation", showAllPaths))
			execEnv = append(execEnv, fmt.Sprintf("SHOW_ALL=%v", showAllPaths))
		}

		if timestamps {
			log.Debug(i18n.G("including TIMESTAMPS=%v in backupbot exec invocation", timestamps))
			execEnv = append(execEnv, fmt.Sprintf("TIMESTAMPS=%v", timestamps))
		}

		if _, err = internal.RunBackupCmdRemote(cl, "ls", targetContainer.ID, execEnv); err != nil {
			log.Fatal(err)
		}
	},
}

// translators: `abra app backup download` aliases. use a comma separated list of aliases with
// no spaces in between
var appBackupDownloadAliases = i18n.G("d")

var AppBackupDownloadCommand = &cobra.Command{
	// translators: `app backup download` command
	Use:     i18n.G("download <domain> [flags]"),
	Aliases: strings.Split(appBackupDownloadAliases, ","),
	// translators: Short description for `app backup download` command
	Short: i18n.G("Download a snapshot"),
	Long: i18n.G(`Downloads a backup.tar.gz to the current working directory.

"--volumes/-v" includes data contained in volumes alongide paths specified in
"backupbot.backup.path" labels.`),
	Args: cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)

		if err := app.Recipe.Ensure(internal.GetEnsureContext()); err != nil {
			log.Fatal(err)
		}

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

		targetContainer, err := internal.RetrieveBackupBotContainer(cl)
		if err != nil {
			log.Fatal(err)
		}

		execEnv := []string{
			fmt.Sprintf("SERVICE=%s", app.Domain),
			"MACHINE_LOGS=true",
		}

		if snapshot != "" {
			log.Debug(i18n.G("including SNAPSHOT=%s in backupbot exec invocation", snapshot))
			execEnv = append(execEnv, fmt.Sprintf("SNAPSHOT=%s", snapshot))
		}

		if includePath != "" {
			log.Debug(i18n.G("including INCLUDE_PATH=%s in backupbot exec invocation", includePath))
			execEnv = append(execEnv, fmt.Sprintf("INCLUDE_PATH=%s", includePath))
		}

		if includeSecrets {
			log.Debug(i18n.G("including SECRETS=%v in backupbot exec invocation", includeSecrets))
			execEnv = append(execEnv, fmt.Sprintf("SECRETS=%v", includeSecrets))
		}

		if includeVolumes {
			log.Debug(i18n.G("including VOLUMES=%v in backupbot exec invocation", includeVolumes))
			execEnv = append(execEnv, fmt.Sprintf("VOLUMES=%v", includeVolumes))
		}

		if _, err := internal.RunBackupCmdRemote(cl, "download", targetContainer.ID, execEnv); err != nil {
			log.Fatal(err)
		}

		remoteBackupDir := "/tmp/backup.tar.gz"
		currentWorkingDir := "."
		if err = CopyFromContainer(cl, targetContainer.ID, remoteBackupDir, currentWorkingDir); err != nil {
			log.Fatal(err)
		}
	},
}

// translators: `abra app backup create` aliases. use a comma separated list of aliases with
// no spaces in between
var appBackupCreateAliases = i18n.G("c")

var AppBackupCreateCommand = &cobra.Command{
	// translators: `app backup create` command
	Use:     i18n.G("create <domain> [flags]"),
	Aliases: strings.Split(appBackupCreateAliases, ","),
	// translators: Short description for `app backup create` command
	Short: i18n.G("Create a new snapshot"),
	Args:  cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)

		if err := app.Recipe.Ensure(internal.GetEnsureContext()); err != nil {
			log.Fatal(err)
		}

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

		targetContainer, err := internal.RetrieveBackupBotContainer(cl)
		if err != nil {
			log.Fatal(err)
		}

		execEnv := []string{
			fmt.Sprintf("SERVICE=%s", app.Domain),
			"MACHINE_LOGS=true",
		}

		if retries != "" {
			log.Debug(i18n.G("including RETRIES=%s in backupbot exec invocation", retries))
			execEnv = append(execEnv, fmt.Sprintf("RETRIES=%s", retries))
		}

		if _, err := internal.RunBackupCmdRemote(cl, "create", targetContainer.ID, execEnv); err != nil {
			log.Fatal(err)
		}
	},
}

// translators: `abra app backup snapshots` aliases. use a comma separated list of aliases with
// no spaces in between
var appBackupSnapshotsAliases = i18n.G("s")

var AppBackupSnapshotsCommand = &cobra.Command{
	// translators: `app backup snapshots` command
	Use:     i18n.G("snapshots <domain> [flags]"),
	Aliases: strings.Split(appBackupSnapshotsAliases, ","),
	// translators: Short description for `app backup snapshots` command
	Short: i18n.G("List all snapshots"),
	Args:  cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.AppNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)

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

		targetContainer, err := internal.RetrieveBackupBotContainer(cl)
		if err != nil {
			log.Fatal(err)
		}

		execEnv := []string{
			fmt.Sprintf("SERVICE=%s", app.Domain),
			"MACHINE_LOGS=true",
		}

		if _, err = internal.RunBackupCmdRemote(cl, "snapshots", targetContainer.ID, execEnv); err != nil {
			log.Fatal(err)
		}
	},
}

// translators: `abra app backup` aliases. use a comma separated list of aliases with
// no spaces in between
var appBackupAliases = i18n.G("b")

var AppBackupCommand = &cobra.Command{
	// translators: `app backup` command group
	Use:     i18n.G("backup [cmd] [args] [flags]"),
	Aliases: strings.Split(appBackupAliases, ","),
	// translators: Short description for `app backup` command group
	Short: i18n.G("Manage app backups"),
}

var (
	snapshot       string
	retries        string
	includePath    string
	showAllPaths   bool
	timestamps     bool
	includeSecrets bool
	includeVolumes bool
)

func init() {
	AppBackupListCommand.Flags().StringVarP(
		&snapshot,
		i18n.G("snapshot"),
		i18n.G("s"),
		"",
		i18n.G("list specific snapshot"),
	)

	AppBackupListCommand.Flags().BoolVarP(
		&showAllPaths,
		i18n.G("all"),
		i18n.GC("a", "app backup list"),
		false,
		i18n.G("show all paths"),
	)

	AppBackupListCommand.Flags().BoolVarP(
		&timestamps,
		i18n.G("timestamps"),
		i18n.G("t"),
		false,
		i18n.G("include timestamps"),
	)

	AppBackupDownloadCommand.Flags().StringVarP(
		&snapshot,
		i18n.G("snapshot"),
		i18n.G("s"),
		"",
		i18n.G("list specific snapshot"),
	)

	AppBackupDownloadCommand.Flags().StringVarP(
		&includePath,
		i18n.G("path"),
		i18n.G("p"),
		"",
		i18n.G("volumes path"),
	)

	AppBackupDownloadCommand.Flags().BoolVarP(
		&includeSecrets,
		i18n.G("secrets"),
		i18n.G("S"),
		false,
		i18n.G("include secrets"),
	)

	AppBackupDownloadCommand.Flags().BoolVarP(
		&includeVolumes,
		i18n.G("volumes"),
		i18n.G("v"),
		false,
		i18n.G("include volumes"),
	)

	AppBackupDownloadCommand.Flags().BoolVarP(
		&internal.Chaos,
		i18n.G("chaos"),
		i18n.G("C"),
		false,
		i18n.G("ignore uncommitted recipes changes"),
	)

	AppBackupCreateCommand.Flags().StringVarP(
		&retries,
		i18n.G("retries"),
		i18n.G("r"),
		"1",
		i18n.G("number of retry attempts"),
	)

	AppBackupCreateCommand.Flags().BoolVarP(
		&internal.Chaos,
		i18n.G("chaos"),
		i18n.G("C"),
		false,
		i18n.G("ignore uncommitted recipes changes"),
	)
}
