package app

import (
	"context"
	"fmt"

	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/config"
	"coopcloud.tech/abra/pkg/envfile"
	"coopcloud.tech/abra/pkg/lint"
	stack "coopcloud.tech/abra/pkg/upstream/stack"
	"coopcloud.tech/tagcmp"

	"coopcloud.tech/abra/cli/internal"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/log"
	"github.com/AlecAivazis/survey/v2"
	"github.com/urfave/cli/v3"
)

var appRollbackCommand = cli.Command{
	Name:      "rollback",
	Aliases:   []string{"rl"},
	Usage:     "Roll an app back to a previous version",
	UsageText: "abra app rollback <domain> [<version>] [options]",
	Flags: []cli.Flag{
		internal.ForceFlag,
		internal.NoDomainChecksFlag,
		internal.DontWaitConvergeFlag,
	},
	Before: internal.SubCommandBefore,
	Description: `This command rolls an app back to a previous version.

Unlike "deploy", chaos operations are not supported here. Only recipe versions
are supported values for "[<version>]".

A rollback can be destructive, please ensure you have a copy of your app data
beforehand.`,
	ShellComplete: autocomplete.AppNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		var warnMessages []string

		app := internal.ValidateApp(cmd)
		stackName := app.StackName()

		specificVersion := cmd.Args().Get(1)
		if specificVersion != "" {
			log.Debugf("overriding env file version (%s) with %s", app.Recipe.Version, specificVersion)
			app.Recipe.Version = specificVersion
		}

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

		if err := lint.LintForErrors(app.Recipe); err != nil {
			log.Fatal(err)
		}

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

		log.Debugf("checking whether %s is already deployed", stackName)

		deployMeta, err := stack.IsDeployed(context.Background(), cl, stackName)
		if err != nil {
			log.Fatal(err)
		}

		if !deployMeta.IsDeployed {
			log.Fatalf("%s is not deployed?", app.Name)
		}

		versions, err := app.Recipe.Tags()
		if err != nil {
			log.Fatal(err)
		}

		var availableDowngrades []string
		if deployMeta.Version == "unknown" {
			availableDowngrades = versions
			warnMessages = append(warnMessages, fmt.Sprintf("failed to determine deployed version of %s", app.Name))
		}

		if specificVersion != "" {
			parsedDeployedVersion, err := tagcmp.Parse(deployMeta.Version)
			if err != nil {
				log.Fatalf("'%s' is not a known version for %s", deployMeta.Version, app.Recipe.Name)
			}

			parsedSpecificVersion, err := tagcmp.Parse(specificVersion)
			if err != nil {
				log.Fatalf("'%s' is not a known version for %s", specificVersion, app.Recipe.Name)
			}

			if parsedSpecificVersion.IsGreaterThan(parsedDeployedVersion) && !parsedSpecificVersion.Equals(parsedDeployedVersion) {
				log.Fatalf("%s is not a downgrade for %s?", deployMeta.Version, specificVersion)
			}

			if parsedSpecificVersion.Equals(parsedDeployedVersion) && !internal.Force {
				log.Fatalf("%s is not a downgrade for %s?", deployMeta.Version, specificVersion)
			}

			availableDowngrades = append(availableDowngrades, specificVersion)
		}

		if deployMeta.Version != "unknown" && specificVersion == "" {
			if deployMeta.IsChaos {
				warnMessages = append(warnMessages, fmt.Sprintf("attempting to rollback a chaos deployment"))
			}

			for _, version := range versions {
				parsedDeployedVersion, err := tagcmp.Parse(deployMeta.Version)
				if err != nil {
					log.Fatal(err)
				}

				parsedVersion, err := tagcmp.Parse(version)
				if err != nil {
					log.Fatal(err)
				}

				if parsedVersion.IsLessThan(parsedDeployedVersion) && !(parsedVersion.Equals(parsedDeployedVersion)) {
					availableDowngrades = append(availableDowngrades, version)
				}
			}

			if len(availableDowngrades) == 0 && !internal.Force {
				log.Info("no available downgrades")
				return nil
			}
		}

		var chosenDowngrade string
		if len(availableDowngrades) > 0 {
			if internal.Force || internal.NoInput || specificVersion != "" {
				chosenDowngrade = availableDowngrades[len(availableDowngrades)-1]
				log.Debugf("choosing %s as version to downgrade to (--force/--no-input)", chosenDowngrade)
			} else {
				msg := fmt.Sprintf("please select a downgrade (version: %s):", deployMeta.Version)
				if deployMeta.IsChaos {
					msg = fmt.Sprintf("please select a downgrade (version: %s, chaosVersion: %s):", deployMeta.Version, deployMeta.ChaosVersion)
				}

				prompt := &survey.Select{
					Message: msg,
					Options: internal.ReverseStringList(availableDowngrades),
				}

				if err := survey.AskOne(prompt, &chosenDowngrade); err != nil {
					return err
				}
			}
		}

		log.Debugf("choosing %s as version to rollback", chosenDowngrade)
		if _, err := app.Recipe.EnsureVersion(chosenDowngrade); err != nil {
			log.Fatal(err)
		}

		abraShEnv, err := envfile.ReadAbraShEnvVars(app.Recipe.AbraShPath)
		if err != nil {
			log.Fatal(err)
		}
		for k, v := range abraShEnv {
			app.Env[k] = v
		}

		composeFiles, err := app.Recipe.GetComposeFiles(app.Env)
		if err != nil {
			log.Fatal(err)
		}

		deployOpts := stack.Deploy{
			Composefiles: composeFiles,
			Namespace:    stackName,
			Prune:        false,
			ResolveImage: stack.ResolveImageAlways,
			Detach:       false,
		}

		compose, err := appPkg.GetAppComposeConfig(app.Name, deployOpts, app.Env)
		if err != nil {
			log.Fatal(err)
		}

		appPkg.ExposeAllEnv(stackName, compose, app.Env)
		appPkg.SetRecipeLabel(compose, stackName, app.Recipe.Name)
		appPkg.SetChaosLabel(compose, stackName, internal.Chaos)
		appPkg.SetChaosVersionLabel(compose, stackName, chosenDowngrade)
		appPkg.SetUpdateLabel(compose, stackName, app.Env)

		chaosVersion := config.CHAOS_DEFAULT
		if deployMeta.IsChaos {
			chaosVersion = deployMeta.ChaosVersion
		}

		// NOTE(d1): no release notes implemeneted for rolling back
		if err := internal.NewVersionOverview(
			app,
			warnMessages,
			"rollback",
			deployMeta.Version,
			chaosVersion,
			chosenDowngrade,
			""); err != nil {
			log.Fatal(err)
		}

		if err := stack.RunDeploy(cl, deployOpts, compose, stackName, internal.DontWaitConverge); err != nil {
			log.Fatal(err)
		}

		app.Recipe.Version = chosenDowngrade
		log.Debugf("choosing %s as version to save to env file", app.Recipe.Version)
		if err := app.WriteRecipeVersion(app.Recipe.Version, false); err != nil {
			log.Fatalf("writing new recipe version in env file: %s", err)
		}

		return nil
	},
}
