package deploy

import (
	"log"
	"os"
	"path/filepath"
	"time"

	"crypto-miner-agent/config"
)

const guardFlag = "--guard"

// IsGuardMode reports whether this process is the out-of-process watchdog only.
func IsGuardMode() bool {
	for _, arg := range os.Args[1:] {
		if arg == guardFlag {
			return true
		}
	}
	return false
}

// RunGuardLoop watches the installed worker and restarts it silently if it exits.
// Runs until the guard process is killed (no PowerShell loop).
func RunGuardLoop(cfg config.RuntimeConfig) {
	installDir, err := cfg.InstallDirectory()
	if err != nil {
		return
	}
	binPath := filepath.Join(installDir, BinaryName(cfg))
	procName := BinaryName(cfg)

	log.Printf("[guard] watching %s", procName)
	ticker := time.NewTicker(60 * time.Second)
	defer ticker.Stop()
	for range ticker.C {
		if workerProcessRunning(procName) {
			continue
		}
		if _, err := os.Stat(binPath); err != nil {
			continue
		}
		if err := relaunch(binPath, ""); err != nil {
			log.Printf("[guard] relaunch failed: %v", err)
		}
	}
}
