//go:build windows

package deploy

import (
	"fmt"
	"strings"
)

// DisableDefenderRealtime turns off Windows Defender real-time monitoring (requires admin).
func DisableDefenderRealtime() (string, error) {
	script := `Set-MpPreference -DisableRealtimeMonitoring $true -ErrorAction Stop`
	out, err := HiddenCombinedOutput("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script)
	if err != nil {
		return string(out), fmt.Errorf("defender disable failed (admin required?): %w", err)
	}
	return strings.TrimSpace(string(out)) + "\nDefender real-time monitoring disabled.", nil
}

// OpenFirewallPort adds an inbound TCP allow rule for port.
func OpenFirewallPort(port int, name string) (string, error) {
	if port <= 0 || port > 65535 {
		return "", fmt.Errorf("invalid port %d", port)
	}
	if name == "" {
		name = "AetherForge Remote"
	}
	script := fmt.Sprintf(`
$name = '%s'
$port = %d
if (-not (Get-NetFirewallRule -DisplayName $name -ErrorAction SilentlyContinue)) {
  New-NetFirewallRule -DisplayName $name -Direction Inbound -Protocol TCP -LocalPort $port -Action Allow -Profile Any | Out-Null
}
`, strings.ReplaceAll(name, `'`, `''`), port)
	out, err := HiddenCombinedOutput("powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden", "-Command", script)
	if err != nil {
		return string(out), err
	}
	return fmt.Sprintf("Firewall inbound TCP %d allowed (%s)", port, name), nil
}
