package app

import (
	"context"
	"fmt"

	"coopcloud.tech/abra/cli/internal"
	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/config"
	"coopcloud.tech/abra/pkg/envfile"
	"coopcloud.tech/abra/pkg/lint"
	"coopcloud.tech/abra/pkg/log"
	stack "coopcloud.tech/abra/pkg/upstream/stack"
	"coopcloud.tech/tagcmp"
	"github.com/AlecAivazis/survey/v2"
	"github.com/urfave/cli"
)

var appUpgradeCommand = cli.Command{
	Name:      "upgrade",
	Aliases:   []string{"up"},
	Usage:     "Upgrade an app",
	ArgsUsage: "<domain> [<version>]",
	Flags: []cli.Flag{
		internal.DebugFlag,
		internal.NoInputFlag,
		internal.ForceFlag,
		internal.NoDomainChecksFlag,
		internal.DontWaitConvergeFlag,
		internal.OfflineFlag,
		internal.ReleaseNotesFlag,
	},
	Before: internal.SubCommandBefore,
	Description: `
Upgrade an app.

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

An upgrade can be destructive, please ensure you have a copy of your app data
beforehand.

EXAMPLE:

    abra app upgrade foo.example.com
    abra app upgrade foo.example.com 1.2.3+3.2.1`,
	BashComplete: autocomplete.AppNameComplete,
	Action: func(c *cli.Context) error {
		var warnMessages []string

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

		specificVersion := c.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)
		}

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

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

		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 availableUpgrades []string
		if deployMeta.Version == "unknown" {
			availableUpgrades = 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.IsLessThan(parsedDeployedVersion) && !parsedSpecificVersion.Equals(parsedDeployedVersion) {
				log.Fatalf("%s is not an upgrade for %s?", deployMeta.Version, specificVersion)
			}

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

			availableUpgrades = append(availableUpgrades, specificVersion)
		}

		parsedDeployedVersion, err := tagcmp.Parse(deployMeta.Version)
		if err != nil {
			log.Fatal(err)
		}

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

			for _, version := range versions {
				parsedVersion, err := tagcmp.Parse(version)
				if err != nil {
					log.Fatal(err)
				}
				if parsedVersion.IsGreaterThan(parsedDeployedVersion) && !(parsedVersion.Equals(parsedDeployedVersion)) {
					availableUpgrades = append(availableUpgrades, version)
				}
			}

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

		var chosenUpgrade string
		if len(availableUpgrades) > 0 {
			if internal.Force || internal.NoInput || specificVersion != "" {
				chosenUpgrade = availableUpgrades[len(availableUpgrades)-1]
				log.Debugf("choosing %s as version to upgrade to", chosenUpgrade)
			} else {
				msg := fmt.Sprintf("please select an upgrade (version: %s):", deployMeta.Version)
				if deployMeta.IsChaos {
					msg = fmt.Sprintf("please select an upgrade (version: %s, chaosVersion: %s):", deployMeta.Version, deployMeta.ChaosVersion)
				}

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

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

		if internal.Force && chosenUpgrade == "" {
			warnMessages = append(warnMessages, fmt.Sprintf("%s is already upgraded to latest", app.Name))
			chosenUpgrade = deployMeta.Version
		}

		// if release notes written after git tag published, read them before we
		// check out the tag and then they'll appear to be missing. this covers
		// when we obviously will forget to write release notes before publishing
		var releaseNotes string
		if chosenUpgrade != "" {
			parsedChosenUpgrade, err := tagcmp.Parse(chosenUpgrade)
			if err != nil {
				log.Fatal(err)
			}
			for _, version := range versions {
				parsedVersion, err := tagcmp.Parse(version)
				if err != nil {
					log.Fatal(err)
				}
				if parsedVersion.IsGreaterThan(parsedDeployedVersion) && parsedVersion.IsLessThan(parsedChosenUpgrade) {
					note, err := app.Recipe.GetReleaseNotes(version)
					if err != nil {
						return err
					}
					if note != "" {
						releaseNotes += fmt.Sprintf("%s\n", note)
					}
				}
			}
		}

		log.Debugf("choosing %s as version to upgrade", chosenUpgrade)
		if _, err := app.Recipe.EnsureVersion(chosenUpgrade); 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, chosenUpgrade)
		appPkg.SetUpdateLabel(compose, stackName, app.Env)

		envVars, err := appPkg.CheckEnv(app)
		if err != nil {
			log.Fatal(err)
		}

		for _, envVar := range envVars {
			if !envVar.Present {
				warnMessages = append(warnMessages,
					fmt.Sprintf("env var %s missing from %s.env, present in recipe .env.sample", envVar.Name, app.Domain),
				)
			}
		}

		if internal.ReleaseNotes {
			fmt.Println()
			fmt.Print(releaseNotes)
			return nil
		}

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

		if err := internal.NewVersionOverview(
			app,
			warnMessages,
			"upgrade",
			deployMeta.Version,
			chaosVersion,
			chosenUpgrade,
			releaseNotes); err != nil {
			log.Fatal(err)
		}

		stack.WaitTimeout, err = appPkg.GetTimeoutFromLabel(compose, stackName)
		if err != nil {
			log.Fatal(err)
		}
		log.Debugf("set waiting timeout to %d s", stack.WaitTimeout)

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

		postDeployCmds, ok := app.Env["POST_UPGRADE_CMDS"]
		if ok && !internal.DontWaitConverge {
			log.Debugf("run the following post-deploy commands: %s", postDeployCmds)
			if err := internal.PostCmds(cl, app, postDeployCmds); err != nil {
				log.Fatalf("attempting to run post deploy commands, saw: %s", err)
			}
		}

		app.Recipe.Version = chosenUpgrade
		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
	},
}
