package git

import (
	"path"

	"coopcloud.tech/abra/pkg/config"
	"github.com/go-git/go-git/v5"
	"github.com/go-git/go-git/v5/plumbing"
	"github.com/sirupsen/logrus"
)

// GetRecipeHead retrieves latest HEAD metadata.
func GetRecipeHead(recipeName string) (*plumbing.Reference, error) {
	recipeDir := path.Join(config.ABRA_DIR, "apps", recipeName)

	repo, err := git.PlainOpen(recipeDir)
	if err != nil {
		return nil, err
	}

	head, err := repo.Head()
	if err != nil {
		return nil, err
	}

	return head, nil
}

// IsClean checks if a repo has unstaged changes
func IsClean(recipeName string) (bool, error) {
	recipeDir := path.Join(config.ABRA_DIR, "apps", recipeName)

	repo, err := git.PlainOpen(recipeDir)
	if err != nil {
		return false, err
	}

	worktree, err := repo.Worktree()
	if err != nil {
		return false, err
	}

	status, err := worktree.Status()
	if err != nil {
		return false, err
	}

	if status.String() != "" {
		logrus.Debugf("discovered git status for %s repository: %s", recipeName, status.String())
	} else {
		logrus.Debugf("discovered clean git status for %s repository", recipeName)
	}

	return status.IsClean(), nil
}