package subprocessenv

import (
	"fmt"
	"strings"
)

type Logf func(format string, args ...any)

func Configure(executable string, setDir func(string) error, loadDLL func(string) error, logf Logf) error {
	dir := executableDir(executable)
	if err := setDir(dir); err != nil {
		return fmt.Errorf("set dll directory %q: %w", dir, err)
	}

	wintunPath := joinWindowsPath(dir, "wintun.dll")
	if err := loadDLL(wintunPath); err != nil && logf != nil {
		logf("Error pre-loading %q: %v", wintunPath, err)
	}
	return nil
}

func executableDir(executable string) string {
	idx := strings.LastIndexAny(executable, `\/`)
	if idx < 0 {
		return "."
	}
	if idx == 0 {
		return executable[:1]
	}
	return executable[:idx]
}

func joinWindowsPath(dir, base string) string {
	if dir == "" || dir == "." {
		return base
	}
	if strings.HasSuffix(dir, `\`) || strings.HasSuffix(dir, `/`) {
		return dir + base
	}
	return dir + `\` + base
}
