package buildverify

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

func desktopRoot(t *testing.T) string {
	t.Helper()
	_, file, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("runtime.Caller failed")
	}
	return filepath.Clean(filepath.Join(filepath.Dir(file), "..", ".."))
}

func repoRoot(t *testing.T) string {
	t.Helper()
	return filepath.Dir(desktopRoot(t))
}

func readFile(t *testing.T, path string) string {
	t.Helper()
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read %s: %v", path, err)
	}
	return string(data)
}

func targetBody(t *testing.T, makefile, target string) string {
	t.Helper()
	lines := strings.Split(makefile, "\n")
	start := -1
	for i, line := range lines {
		if strings.HasPrefix(line, target+":") {
			start = i
			break
		}
	}
	if start < 0 {
		t.Fatalf("target %q not found", target)
	}
	end := len(lines)
	for i := start + 1; i < len(lines); i++ {
		line := lines[i]
		if line != "" && line[0] != '\t' && !strings.HasPrefix(line, " ") {
			end = i
			break
		}
	}
	return strings.Join(lines[start:end], "\n")
}
