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

var AppLogsCommand = &cobra.Command{
	Use:     "logs <domain> [service] [flags]",
	Aliases: []string{"l"},
	Short:   "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 {
				errMsg := fmt.Sprintf("autocomplete failed: %s", err)
				return []string{errMsg}, 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.Fatalf("%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,
		"stderr",
		"s",
		false,
		"only tail stderr",
	)

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