package orch

import (
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

func initGitRepo(t *testing.T) string {
	t.Helper()

	repoPath := filepath.Join(t.TempDir(), "repo")
	if err := os.MkdirAll(repoPath, 0o755); err != nil {
		t.Fatalf("mkdir repo path: %v", err)
	}

	runGitCommand(t, repoPath, "init")
	runGitCommand(t, repoPath, "config", "user.email", "test@example.com")
	runGitCommand(t, repoPath, "config", "user.name", "Test User")

	readmePath := filepath.Join(repoPath, "README.md")
	if err := os.WriteFile(readmePath, []byte("hello\n"), 0o644); err != nil {
		t.Fatalf("write README.md: %v", err)
	}

	runGitCommand(t, repoPath, "add", "README.md")
	runGitCommand(t, repoPath, "commit", "-m", "init")

	return repoPath
}

func gitHeadCommit(t *testing.T, repoPath string) string {
	t.Helper()

	cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--verify", "HEAD^{commit}")
	output, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("git rev-parse HEAD in %s: %v\n%s", repoPath, err, output)
	}
	return strings.TrimSpace(string(output))
}

func runGitCommand(t *testing.T, repoPath string, args ...string) {
	t.Helper()

	cmd := exec.Command("git", append([]string{"-C", repoPath}, args...)...)
	output, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("git %v in %s: %v\n%s", args, repoPath, err, output)
	}
}
