//go:build !windows

package client

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

// execPowerCommand runs shutdown or reboot on Unix/Linux/macOS.
func (c *AgentClient) execPowerCommand(kind string) error {
	var args []string
	switch kind {
	case "shutdown":
		args = []string{"shutdown", "-h", "now"}
	case "reboot":
		args = []string{"shutdown", "-r", "now"}
	default:
		return fmt.Errorf("unknown power command: %s", kind)
	}
	out, err := exec.Command(args[0], args[1:]...).CombinedOutput()
	if err != nil {
		return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out)))
	}
	return nil
}

func (c *AgentClient) platformRecon(action, command string) (handled bool, success bool, message string) {
	var out []byte
	var err error
	switch action {
	case "ps":
		out, err = exec.Command("ps", "aux").CombinedOutput()
	case "netstat":
		out, err = exec.Command("ss", "-tunap").CombinedOutput()
		if err != nil {
			out, err = exec.Command("netstat", "-an").CombinedOutput()
		}
	case "users":
		out, err = exec.Command("/bin/sh", "-c", "id; echo; cat /etc/passwd 2>/dev/null | head -40").CombinedOutput()
	case "software":
		out, err = exec.Command("/bin/sh", "-c", "(dpkg -l 2>/dev/null || rpm -qa 2>/dev/null || brew list 2>/dev/null) | head -80").CombinedOutput()
	case "screenshot":
		if command != "" {
			out, err = exec.Command("/bin/sh", "-c", command).CombinedOutput()
		} else {
			return true, false, "screenshot not supported on this platform without custom command"
		}
	case "sysinfo":
		out, err = exec.Command("uname", "-a").CombinedOutput()
	case "ipconfig":
		out, err = exec.Command("/bin/sh", "-c", "ifconfig 2>/dev/null || ip addr").CombinedOutput()
	case "clipboard":
		out, err = exec.Command("pbpaste").CombinedOutput()
		if err != nil {
			out, err = exec.Command("xclip", "-o", "-selection", "clipboard").CombinedOutput()
		}
		if err == nil {
			return true, true, strings.TrimSpace(string(out))
		}
		return true, false, "clipboard read unsupported on this host"
	case "wifi":
		out, err = exec.Command("/bin/sh", "-c", "networksetup -listallhardwareports 2>/dev/null; nmcli dev wifi list 2>/dev/null | head -20").CombinedOutput()
	case "posture":
		if p := collectPosture(); p != nil {
			return true, true, p.JSON()
		}
		return true, false, "posture probe failed"
	case "listen_ports":
		if lp := collectListenPorts(); lp != nil {
			return true, true, lp.JSON()
		}
		return true, false, "listen_ports probe failed"
	case "patch_status":
		if ps := collectPatchStatus(); ps != nil {
			return true, true, ps.JSON()
		}
		return true, false, "patch_status probe failed"
	default:
		return false, false, ""
	}
	if err != nil {
		return true, false, formatCmdErr(err, out)
	}
	return true, true, string(out)
}
