package repositoryset

import (
	"fmt"
	"os"

	"gh_foundations/cmd/gen/common"
	githubfoundations "gh_foundations/internal/pkg/types/github_foundations"

	zone "github.com/lrstanley/bubblezone"
	"github.com/spf13/cobra"
)

var terraformerStateFile string

var GenRepositorySetCmd = &cobra.Command{
	Use:   "repository_set",
	Short: "Generates an hcl file that contains a repository set input. Can be run interactively or with a terraformer file input",
	Long:  `Generates an hcl file that contains a repository set input. Can be run interactively or with a terraformer file input using the --terraformer-file flag. If run with a terraformer file it will generate hcl for all repositories in the state file generated by terraformer.`,
	Args: func(cmd *cobra.Command, args []string) error {
		if terraformerStateFile != "" {
			if _, err := os.Stat(terraformerStateFile); err != nil {
				return err
			}
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		zone.NewGlobal()
		var repositorySet *githubfoundations.RepositorySetInput
		if terraformerStateFile != "" {
			repositorySet = genFromTerraformerFile(terraformerStateFile)
		} else {
			var err error
			repositorySet, err = runInteractive()
			if err != nil {
				fmt.Println("Error running interactive mode:", err)
				os.Exit(1)
			}
		}

		if err := common.OutputHCLToFile("repository_set.inputs.hcl", repositorySet); err != nil {
			fmt.Println("Error writing hcl file:", err)
			os.Exit(1)
		}
	},
}

func init() {
	GenRepositorySetCmd.Flags().StringVarP(&terraformerStateFile, "terraformer-file", "f", "", "Terraformer state file to generate repository_set hcl from")
}
