package infra

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

// GoBuildBinary compila un binario Go desde projectDir hacia outputPath.
// Si ldflags está vacío usa "-s -w" (strip debug info). Si outputPath está vacío
// usa "build/{dirname}" dentro del projectDir. Requiere Go instalado en PATH.
func GoBuildBinary(projectDir, outputPath string, ldflags string, tags string) error {
	if ldflags == "" {
		ldflags = "-s -w"
	}
	if outputPath == "" {
		outputPath = filepath.Join(projectDir, "build", filepath.Base(projectDir))
	}

	// Crear directorio destino si no existe
	if err := os.MkdirAll(filepath.Dir(outputPath), 0o755); err != nil {
		return fmt.Errorf("go_build_binary: crear directorio destino %s: %w", filepath.Dir(outputPath), err)
	}

	args := []string{"build", "-trimpath", "-ldflags=" + ldflags}
	if tags != "" {
		args = append(args, "-tags="+tags)
	}
	args = append(args, "-o", outputPath, ".")

	cmd := exec.Command("go", args...)
	cmd.Dir = projectDir
	cmd.Env = append(os.Environ(), "CGO_ENABLED=0")

	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("go build en %s: %s", projectDir, strings.TrimSpace(string(out)))
	}
	return nil
}
