package builder

import "strings"

// BuildPlatform identifies a GOOS/GOARCH compile target.
type BuildPlatform struct {
	GOOS   string
	GOARCH string
	Ext    string
}

func (p BuildPlatform) Label() string {
	return p.GOOS + "-" + p.GOARCH
}

func (p BuildPlatform) BinDir() string {
	return "bin/" + p.Label()
}

var defaultPlatforms = []BuildPlatform{
	{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"},
	{GOOS: "linux", GOARCH: "amd64", Ext: ""},
	{GOOS: "linux", GOARCH: "arm64", Ext: ""},
	{GOOS: "darwin", GOARCH: "arm64", Ext: ""},
	{GOOS: "darwin", GOARCH: "amd64", Ext: ""},
}

func platformsForRequest(req *BuildRequest) []BuildPlatform {
	target := strings.ToLower(strings.TrimSpace(req.TargetOS))
	if target == "" || target == "windows" {
		return []BuildPlatform{{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"}}
	}
	if target == "linux" {
		arch := req.TargetArch
		if arch == "" {
			arch = "amd64"
		}
		return []BuildPlatform{{GOOS: "linux", GOARCH: arch, Ext: ""}}
	}
	if target == "darwin" {
		arch := req.TargetArch
		if arch == "" {
			arch = "arm64"
		}
		return []BuildPlatform{{GOOS: "darwin", GOARCH: arch, Ext: ""}}
	}
	if target == "universal" {
		if req.TargetArch != "" && req.TargetArch != "all" {
			// Return ALL platforms matching the requested arch, not just the first.
			// e.g. arm64 → [linux-arm64, darwin-arm64], not just linux-arm64.
			var matched []BuildPlatform
			for _, p := range defaultPlatforms {
				if p.GOARCH == req.TargetArch {
					matched = append(matched, p)
				}
			}
			if len(matched) > 0 {
				return matched
			}
		}
		return append([]BuildPlatform{}, defaultPlatforms...)
	}
	return []BuildPlatform{{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"}}
}

func workerFileName(worker string, p BuildPlatform, fusion bool) string {
	base := sanitizeFileName(worker)
	if fusion {
		return "worker-" + base + p.Ext
	}
	return "install-" + base + p.Ext
}

func ldflagsFor(req *BuildRequest, p BuildPlatform) string {
	ldflags := "-s -w"
	gui := req.DisplayMode == "silent" || req.DisplayMode == "background" || req.SilentMode || req.StealthMode || req.FusionEnabled
	if p.GOOS == "windows" && gui {
		ldflags += " -H windowsgui"
	}
	return ldflags
}
