package platform

import (
	"os"
	"os/exec"
	"strings"
)

func fileContains(path, substr string) bool {
	data, err := os.ReadFile(path)
	if err != nil {
		return false
	}
	return strings.Contains(strings.ToLower(string(data)), substr)
}

func execLookPath(name string) (string, error) {
	return exec.LookPath(name)
}

func readOSReleaseName() string {
	data, err := os.ReadFile("/etc/os-release")
	if err != nil {
		return ""
	}
	var pretty, name, version string
	for _, line := range strings.Split(string(data), "\n") {
		key, val, ok := strings.Cut(line, "=")
		if !ok {
			continue
		}
		val = strings.Trim(val, `"'`)
		switch key {
		case "PRETTY_NAME":
			pretty = val
		case "NAME":
			name = val
		case "VERSION_ID":
			version = val
		}
	}
	if pretty != "" {
		return pretty
	}
	if name != "" && version != "" {
		return name + " " + version
	}
	return name
}

func readMacOSVersion() string {
	out, err := exec.Command("sw_vers", "-productVersion").Output()
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(out))
}

func readWindowsVersion() string {
	if v := os.Getenv("OS"); v != "" && strings.Contains(strings.ToLower(v), "windows") {
		// Try to detect Windows 11 vs 10 via build number
		if build := os.Getenv("MUYUE_WIN_BUILD"); build != "" {
			return "Windows " + build
		}
	}
	out, err := exec.Command("cmd", "/c", "ver").Output()
	if err != nil {
		return ""
	}
	s := strings.TrimSpace(string(out))
	if strings.Contains(s, "10.0.22") || strings.Contains(s, "10.0.23") {
		return "Windows 11"
	}
	if strings.Contains(s, "10.0.") {
		return "Windows 10"
	}
	return s
}
