package ignore

import (
	"errors"
	"os"
	"path"

	ignore "github.com/denormal/go-gitignore"
)

const (
	gitIgnore = ".gitignore"
)

var (
	ErrNotFound = errors.New("Not Found")
)

// getIgnore attempts to find and parse a .gitignore file recursively.
// It searches for the .gitignore file starting from the given path and traversing up the directory tree.
// It returns a pointer to the parsed ignore.GitIgnore object if found, otherwise nil.
func FindGitignore(name string) (ignore.GitIgnore, error) {

	for {
		stat, err := os.Stat(name)
		if err != nil {
			return nil, err
		}

		// If the current path is a directory, iterate through its contents.
		if stat.IsDir() {
			dir, err := os.ReadDir(name)
			if err != nil {
				name, _ = path.Split(name)
				if name == "" {
					return nil, ErrNotFound
				}
			}
			for _, e := range dir {

				if !e.IsDir() && e.Name() == gitIgnore {
					if ignore, err := ignore.NewFromFile(path.Join(name, e.Name())); err == nil {
						return ignore, nil
					}
					return nil, err
				}
			}

		}

		// If the current path is the .gitignore file itself.
		if stat.Name() == gitIgnore {
			if ignore, err := ignore.NewFromFile(name); err == nil {
				return ignore, nil
			}
			return nil, err
		}

		name, _ = path.Split(name)
		if name == "" {
			return nil, ErrNotFound
		}

	}
}
