package gitrepo

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"os/exec"
	"strings"
)

// IsAncestor zegt of ancestor een voorouder is van descendant, inclusief
// het geval dat beide dezelfde commit zijn.
func IsAncestor(ctx context.Context, gitBin, dir, ancestor, descendant string) bool {
	if ancestor == "" || descendant == "" {
		return false
	}
	cmd := exec.CommandContext(ctx, gitBin, "-C", dir, "merge-base", "--is-ancestor", ancestor, descendant)
	return cmd.Run() == nil
}

// Conflicts zegt of ours en theirs niet schoon samen te voegen zijn.
// ours is de doelbranch, theirs de bron. Een ontbrekende revisie is een fout.
func Conflicts(ctx context.Context, gitBin, dir, ours, theirs string) (bool, error) {
	cmd := exec.CommandContext(ctx, gitBin, "-C", dir, "merge-tree", "--write-tree", ours, theirs)
	out, err := cmd.CombinedOutput()
	if err == nil {
		return false, nil
	}
	var exit *exec.ExitError
	if errors.As(err, &exit) && exit.ExitCode() == 1 {
		return true, nil
	}
	if errors.As(err, &exit) && exit.ExitCode() == 129 || bytes.Contains(out, []byte("unknown option")) {
		return conflictsLegacy(ctx, gitBin, dir, ours, theirs)
	}
	return false, fmt.Errorf("merge-tree: %w (%s)", err, strings.TrimSpace(string(out)))
}

func conflictsLegacy(ctx context.Context, gitBin, dir, ours, theirs string) (bool, error) {
	base, err := run(ctx, gitBin, nil, "-C", dir, "merge-base", ours, theirs)
	if err != nil {
		return false, err
	}
	out, err := run(ctx, gitBin, nil, "-C", dir, "merge-tree", strings.TrimSpace(base), ours, theirs)
	if err != nil {
		return false, err
	}
	return strings.Contains(out, "changed in both") || strings.Contains(out, "CONFLICT"), nil
}
