//go:build windows

package platform

import (
	"runtime"
	"strings"

	"github.com/klauspost/cpuid/v2"
	"golang.org/x/sys/windows/registry"
)

func detectCPUWindows() CPUInfo {
	info := CPUInfo{
		Features: []string{},
	}

	// Check for ARM64 Windows first
	if runtime.GOARCH == "arm64" {
		info.Vendor = "ARM"
		info.Features = []string{"neon", "arm64"}
		info.ArchitectureLevel = "arm64"

		// Try to get CPU name from registry
		k, err := registry.OpenKey(registry.LOCAL_MACHINE,
			`HARDWARE\DESCRIPTION\System\CentralProcessor\0`,
			registry.QUERY_VALUE)
		if err == nil {
			defer k.Close()
			name, _, err := k.GetStringValue("ProcessorNameString")
			if err == nil {
				info.Model = strings.TrimSpace(name)
			}
		}
		return info
	}

	// Get CPU brand string from Windows Registry (x86-64)
	k, err := registry.OpenKey(registry.LOCAL_MACHINE,
		`HARDWARE\DESCRIPTION\System\CentralProcessor\0`,
		registry.QUERY_VALUE)
	if err == nil {
		defer k.Close()
		name, _, err := k.GetStringValue("ProcessorNameString")
		if err == nil {
			info.Model = strings.TrimSpace(name)
		}
	}

	// Use cpuid for feature detection (pure Go, no CGo)
	cpu := cpuid.CPU

	// Detect vendor
	switch cpu.VendorString {
	case "GenuineIntel":
		info.Vendor = "Intel"
	case "AuthenticAMD", "HygonGenuine":
		info.Vendor = "AMD"
	case "CentaurHauls":
		info.Vendor = "VIA"
	default:
		info.Vendor = cpu.VendorString
	}

	// Build features list from cpuid
	var features []string

	// Always include base x86-64 features
	features = append(features, "mmx", "sse", "sse2", "sse3", "ssse3", "sse4_1", "sse4_2")

	if cpu.Supports(cpuid.AVX) {
		features = append(features, "avx")
	}
	if cpu.Supports(cpuid.AVX2) {
		features = append(features, "avx2")
	}
	if cpu.Supports(cpuid.AVX512F) {
		features = append(features, "avx512f")
	}
	if cpu.Supports(cpuid.FMA3) {
		features = append(features, "fma3")
	}

	info.Features = features

	// Set x86-64 architecture level from cpuid
	level := cpu.X64Level()
	switch level {
	case 4:
		info.ArchitectureLevel = "x86-64-v4"
	case 3:
		info.ArchitectureLevel = "x86-64-v3"
	case 2:
		info.ArchitectureLevel = "x86-64-v2"
	default:
		info.ArchitectureLevel = "x86-64"
	}

	return info
}
