package internal

import (
	"fmt"
	"os"
	"strings"

	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/log"
	"github.com/AlecAivazis/survey/v2"
	"github.com/charmbracelet/lipgloss"
	dockerClient "github.com/docker/docker/client"
)

var borderStyle = lipgloss.NewStyle().
	BorderStyle(lipgloss.ThickBorder()).
	Padding(0, 1, 0, 1).
	MaxWidth(79).
	BorderForeground(lipgloss.Color("63"))

var headerStyle = lipgloss.NewStyle().
	Underline(true).
	Bold(true)

var leftStyle = lipgloss.NewStyle().
	Bold(true)

var rightStyle = lipgloss.NewStyle()

// horizontal is a JoinHorizontal helper function.
func horizontal(left, mid, right string) string {
	return lipgloss.JoinHorizontal(lipgloss.Left, left, mid, right)
}

// NewVersionOverview shows an upgrade or downgrade overview
func NewVersionOverview(
	app appPkg.App,
	warnMessages []string,
	kind,
	currentVersion,
	chaosVersion,
	newVersion,
	releaseNotes string) error {
	deployConfig := "compose.yml"
	if composeFiles, ok := app.Env["COMPOSE_FILE"]; ok {
		deployConfig = strings.Join(strings.Split(composeFiles, ":"), "\n")
	}

	server := app.Server
	if app.Server == "default" {
		server = "local"
	}

	body := strings.Builder{}
	body.WriteString(
		borderStyle.Render(
			lipgloss.JoinVertical(
				lipgloss.Center,
				headerStyle.Render(fmt.Sprintf("%s OVERVIEW", strings.ToUpper(kind))),
				lipgloss.JoinVertical(
					lipgloss.Left,
					horizontal(leftStyle.Render("SERVER"), "   ", rightStyle.Render(server)),
					horizontal(leftStyle.Render("DOMAIN"), "   ", rightStyle.Render(app.Domain)),
					horizontal(leftStyle.Render("RECIPE"), "   ", rightStyle.Render(app.Recipe.Name)),
					horizontal(leftStyle.Render("CONFIG"), "   ", rightStyle.Render(deployConfig)),
					horizontal(leftStyle.Render("VERSION"), "  ", rightStyle.Render(currentVersion)),
					horizontal(leftStyle.Render("CHAOS"), "    ", rightStyle.Render(chaosVersion)),
					horizontal(leftStyle.Render("DEPLOY"), "   ", rightStyle.Padding(0).Render(newVersion)),
				),
			),
		),
	)
	fmt.Println(body.String())

	if releaseNotes != "" && newVersion != "" {
		fmt.Println()
		fmt.Print(releaseNotes)
	} else {
		warnMessages = append(warnMessages, fmt.Sprintf("no release notes available for %s", newVersion))
	}

	for _, msg := range warnMessages {
		log.Warn(msg)
	}

	if NoInput {
		return nil
	}

	response := false
	prompt := &survey.Confirm{Message: "proceed?"}
	if err := survey.AskOne(prompt, &response); err != nil {
		return err
	}

	if !response {
		log.Fatal("deployment cancelled")
	}

	return nil
}

// DeployOverview shows a deployment overview
func DeployOverview(app appPkg.App, warnMessages []string, version, chaosVersion string) error {
	deployConfig := "compose.yml"
	if composeFiles, ok := app.Env["COMPOSE_FILE"]; ok {
		deployConfig = strings.Join(strings.Split(composeFiles, ":"), "\n")
	}

	server := app.Server
	if app.Server == "default" {
		server = "local"
	}

	body := strings.Builder{}
	body.WriteString(
		borderStyle.Render(
			lipgloss.JoinVertical(
				lipgloss.Center,
				headerStyle.Render("DEPLOY OVERVIEW"),
				lipgloss.JoinVertical(
					lipgloss.Left,
					horizontal(leftStyle.Render("SERVER"), "   ", rightStyle.Render(server)),
					horizontal(leftStyle.Render("DOMAIN"), "   ", rightStyle.Render(app.Domain)),
					horizontal(leftStyle.Render("RECIPE"), "   ", rightStyle.Render(app.Recipe.Name)),
					horizontal(leftStyle.Render("CONFIG"), "   ", rightStyle.Render(deployConfig)),
					horizontal(leftStyle.Render("VERSION"), "  ", rightStyle.Render(version)),
					horizontal(leftStyle.Render("CHAOS"), "    ", rightStyle.Padding(0).Render(chaosVersion)),
				),
			),
		),
	)
	fmt.Println(body.String())

	for _, msg := range warnMessages {
		log.Warn(msg)
	}

	if NoInput {
		return nil
	}

	response := false
	prompt := &survey.Confirm{Message: "proceed?"}
	if err := survey.AskOne(prompt, &response); err != nil {
		return err
	}

	if !response {
		log.Fatal("deployment cancelled")
	}

	return nil
}

// PostCmds parses a string of commands and executes them inside of the respective services
// the commands string must have the following format:
// "<service> <command> <arguments>|<service> <command> <arguments>|... "
func PostCmds(cl *dockerClient.Client, app appPkg.App, commands string) error {
	if _, err := os.Stat(app.Recipe.AbraShPath); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf(fmt.Sprintf("%s does not exist for %s?", app.Recipe.AbraShPath, app.Name))
		}
		return err
	}

	for _, command := range strings.Split(commands, "|") {
		commandParts := strings.Split(command, " ")
		if len(commandParts) < 2 {
			return fmt.Errorf(fmt.Sprintf("not enough arguments: %s", command))
		}
		targetServiceName := commandParts[0]
		cmdName := commandParts[1]
		parsedCmdArgs := ""
		if len(commandParts) > 2 {
			parsedCmdArgs = fmt.Sprintf("%s ", strings.Join(commandParts[2:], " "))
		}
		log.Infof("running post-command '%s %s' in container %s", cmdName, parsedCmdArgs, targetServiceName)

		if err := EnsureCommand(app.Recipe.AbraShPath, app.Recipe.Name, cmdName); err != nil {
			return err
		}

		serviceNames, err := appPkg.GetAppServiceNames(app.Name)
		if err != nil {
			return err
		}

		matchingServiceName := false
		for _, serviceName := range serviceNames {
			if serviceName == targetServiceName {
				matchingServiceName = true
			}
		}

		if !matchingServiceName {
			return fmt.Errorf(fmt.Sprintf("no service %s for %s?", targetServiceName, app.Name))
		}

		log.Debugf("running command %s %s within the context of %s_%s", cmdName, parsedCmdArgs, app.StackName(), targetServiceName)

		Tty = true
		if err := RunCmdRemote(cl, app, app.Recipe.AbraShPath, targetServiceName, cmdName, parsedCmdArgs); err != nil {
			return err
		}
	}
	return nil
}
