package commands

import (
	"context"
	"encoding/json"
	"os/exec"
	"strings"
)

// security.malware.active_scans — global count of in-flight maldet scans.
// Each scan runs as a transient `jabali-maldet-scan-<session>.service`
// (security_malware.go), so an active scan == a running unit matching the
// glob. Used by the top-bar Tasks indicator so a running scan shows without
// the caller knowing the session id.

type activeScansResponse struct {
	Active int `json:"active"`
}

func malwareActiveScansHandler(ctx context.Context, _ json.RawMessage) (any, error) {
	out, err := exec.CommandContext(ctx, "systemctl",
		"list-units", "jabali-maldet-scan-*.service",
		"--state=active", "--no-legend", "--plain", "--no-pager",
	).Output()
	if err != nil {
		// list-units exits non-zero with no matches on some systemd builds;
		// treat as "none running" rather than an error.
		return activeScansResponse{Active: 0}, nil
	}
	n := 0
	for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
		if strings.Contains(line, "jabali-maldet-scan-") {
			n++
		}
	}
	return activeScansResponse{Active: n}, nil
}

func init() {
	Default.Register("security.malware.active_scans", malwareActiveScansHandler)
}
