package app

import (
	"context"
	"strings"

	"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/i18n"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/logs"
	"coopcloud.tech/abra/pkg/upstream/stack"
	"github.com/spf13/cobra"
)

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

var AppLogsCommand = &cobra.Command{
	// translators: `app logs` command
	Use:     i18n.G("logs <domain> [service] [flags]"),
	Aliases: strings.Split(appLogsAliases, ","),
	// translators: Short description for `app logs` command
	Short: i18n.G("Tail app logs"),
	Args:  cobra.RangeArgs(1, 2),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		switch l := len(args); l {
		case 0:
			return autocomplete.AppNameComplete()
		case 1:
			app, err := appPkg.Get(args[0])
			if err != nil {
				return []string{i18n.G("autocomplete failed: %s", err)}, cobra.ShellCompDirectiveError
			}
			return autocomplete.ServiceNameComplete(app.Name)
		default:
			return nil, cobra.ShellCompDirectiveDefault
		}
	},
	Run: func(cmd *cobra.Command, args []string) {
		app := internal.ValidateApp(args)
		stackName := app.StackName()

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

		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.Fatal(i18n.G("%s is not deployed?", app.Name))
		}

		var serviceNames []string
		if len(args) == 2 {
			serviceNames = []string{args[1]}
		}

		f, err := app.Filters(true, false, serviceNames...)
		if err != nil {
			log.Fatal(err)
		}

		opts := logs.TailOpts{
			AppName:  app.Name,
			Services: serviceNames,
			StdErr:   stdErr,
			Since:    sinceLogs,
			Filters:  f,
		}

		if err := logs.TailLogs(cl, opts); err != nil {
			log.Fatal(err)
		}
	},
}

var (
	stdErr    bool
	sinceLogs string
)

func init() {
	AppLogsCommand.Flags().BoolVarP(
		&stdErr,
		i18n.G("stderr"),
		i18n.G("s"),
		false,
		i18n.G("only tail stderr"),
	)

	AppLogsCommand.Flags().StringVarP(
		&sinceLogs,
		i18n.G("since"),
		i18n.G("S"),
		"",
		i18n.G("tail logs since YYYY-MM-DDTHH:MM:SSZ"),
	)
}
