package builder

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

func (h *Handler) runGoWinres(dir string, args ...string) ([]byte, error) {
	if h.goWinresPath != "" {
		cmd := exec.Command(h.goWinresPath, args...)
		if dir != "" {
			cmd.Dir = dir
		}
		out, err := cmd.CombinedOutput()
		if err != nil {
			return out, fmt.Errorf("%w (%s)", err, strings.TrimSpace(string(out)))
		}
		return out, nil
	}

	modDir := h.serverModDir
	if modDir == "" {
		modDir = "."
	}
	cmd := exec.Command(h.goBinPath, append([]string{"run", "github.com/tc-hib/go-winres"}, args...)...)
	cmd.Dir = modDir
	if dir != "" {
		cmd.Dir = dir
	}
	out, err := cmd.CombinedOutput()
	if err != nil {
		return out, fmt.Errorf("%w (%s)", err, strings.TrimSpace(string(out)))
	}
	return out, nil
}

func (h *Handler) resolveToolPaths(projectRoot string) {
	if h.goBinPath == "" {
		h.goBinPath = "go"
	}
	if h.serverModDir == "" {
		h.serverModDir = filepath.Join(projectRoot, "server")
	}
	if p, err := exec.LookPath("garble"); err == nil {
		h.garblePath = p
	}
	if p, err := exec.LookPath("go-winres"); err == nil {
		h.goWinresPath = p
	} else if p, err := exec.LookPath("go-winres.exe"); err == nil {
		h.goWinresPath = p
	}
}
