package automationintegration_test

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

	"github.com/pingcap-inc/nexuscrm-controlplane/packs"
)

func setOfficialPackRootForAutomationTest(t *testing.T) {
	t.Helper()
	t.Setenv(packs.OfficialAppPacksRootEnvVar, officialPackRootForAutomationRoot())
}

func ensureOfficialPackRootForAutomationProcess() error {
	return os.Setenv(packs.OfficialAppPacksRootEnvVar, officialPackRootForAutomationRoot())
}

func officialPackRootForAutomationRoot() string {
	if root := strings.TrimSpace(os.Getenv(packs.OfficialAppPacksRootEnvVar)); root != "" {
		return root
	}
	_, file, _, ok := runtime.Caller(0)
	if !ok {
		panic("runtime.Caller failed")
	}
	repoRoot := filepath.Clean(filepath.Join(filepath.Dir(file), "..", "..", "..", ".."))
	sibling := filepath.Join(filepath.Dir(repoRoot), "nexuscrm-app-packs")
	if info, err := os.Stat(sibling); err == nil && info.IsDir() {
		return sibling
	}
	panic("official app packs root is required: set " + packs.OfficialAppPacksRootEnvVar + " or provide sibling checkout " + sibling)
}
