//go:build windows

package util

import (
	"errors"
	"syscall"
	"time"
)

// KillProcess 终止指定 PID。
func KillProcess(pid int) error {
	handle, err := syscall.OpenProcess(syscall.PROCESS_TERMINATE, false, uint32(pid))
	if err != nil {
		return err
	}
	defer syscall.CloseHandle(handle)
	return syscall.TerminateProcess(handle, 0)
}

// ForceKillProcess Windows 下与 KillProcess 相同。
func ForceKillProcess(pid int) error {
	return KillProcess(pid)
}

// ProcessExists 检查进程是否存在。
func ProcessExists(pid int) bool {
	handle, err := syscall.OpenProcess(syscall.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
	if err != nil {
		return !errors.Is(err, syscall.ERROR_INVALID_PARAMETER)
	}
	syscall.CloseHandle(handle)
	return true
}

// WaitProcessExit 等待进程退出。
func WaitProcessExit(pid int, timeout time.Duration) bool {
	deadline := time.Now().Add(timeout)
	for time.Now().Before(deadline) {
		if !ProcessExists(pid) {
			return true
		}
		time.Sleep(200 * time.Millisecond)
	}
	return !ProcessExists(pid)
}
