package recipe

import (
	"bytes"
	"fmt"
	"os"
	"path"
	"text/template"

	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/config"
	"coopcloud.tech/abra/pkg/git"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/recipe"
	"github.com/spf13/cobra"
)

// recipeMetadata is the recipe metadata for the README.md
type recipeMetadata struct {
	Name        string
	Description string
	Category    string
	Status      string
	Image       string
	Healthcheck string
	Backups     string
	Email       string
	Tests       string
	SSO         string
}

var RecipeNewCommand = &cobra.Command{
	Use:     "new <recipe> [flags]",
	Aliases: []string{"n"},
	Short:   "Create a new recipe",
	Long:    `A community managed recipe template is used.`,
	Args:    cobra.ExactArgs(1),
	ValidArgsFunction: func(
		cmd *cobra.Command,
		args []string,
		toComplete string) ([]string, cobra.ShellCompDirective) {
		return autocomplete.RecipeNameComplete()
	},
	Run: func(cmd *cobra.Command, args []string) {
		recipeName := args[0]

		r := recipe.Get(recipeName)
		if _, err := os.Stat(r.Dir); !os.IsNotExist(err) {
			log.Fatalf("%s recipe directory already exists?", r.Dir)
		}

		url := fmt.Sprintf("%s/example.git", config.REPOS_BASE_URL)
		if err := git.Clone(r.Dir, url); err != nil {
			log.Fatal(err)
		}

		gitRepo := path.Join(r.Dir, ".git")
		if err := os.RemoveAll(gitRepo); err != nil {
			log.Fatal(err)
		}
		log.Debugf("removed .git repo in %s", gitRepo)

		meta := newRecipeMeta(recipeName)

		for _, path := range []string{r.ReadmePath, r.SampleEnvPath} {
			tpl, err := template.ParseFiles(path)
			if err != nil {
				log.Fatal(err)
			}

			var templated bytes.Buffer
			if err := tpl.Execute(&templated, meta); err != nil {
				log.Fatal(err)
			}

			if err := os.WriteFile(path, templated.Bytes(), 0o644); err != nil {
				log.Fatal(err)
			}
		}

		if err := git.Init(r.Dir, true, gitName, gitEmail); err != nil {
			log.Fatal(err)
		}

		log.Infof("new recipe '%s' created: %s", recipeName, path.Join(r.Dir))
		log.Info("happy hacking 🎉")
	},
}

// newRecipeMeta creates a new recipeMetadata instance with defaults
func newRecipeMeta(recipeName string) recipeMetadata {
	return recipeMetadata{
		Name:        recipeName,
		Description: "> One line description of the recipe",
		Category:    "Apps",
		Status:      "0",
		Image:       fmt.Sprintf("[`%s`](https://hub.docker.com/r/%s), 4, upstream", recipeName, recipeName),
		Healthcheck: "No",
		Backups:     "No",
		Email:       "No",
		Tests:       "No",
		SSO:         "No",
	}
}

var (
	gitName  string
	gitEmail string
)

func init() {
	RecipeNewCommand.Flags().StringVarP(
		&gitName,
		"git-name",
		"N",
		"",
		"Git (user) name to do commits with",
	)

	RecipeNewCommand.Flags().StringVarP(
		&gitEmail,
		"git-email",
		"e",
		"",
		"Git email name to do commits with",
	)
}
