package infra

import (
	"fmt"
	"strings"
)

// SystemdServiceStatus resultado de consultar el estado de un servicio systemd.
type SystemdServiceStatus struct {
	Unit     string
	Active   string // "active", "inactive", "failed"
	SubState string // "running", "dead", "failed"
	MainPID  string
	Logs     string
}

// SystemdStatus consulta el estado de un servicio systemd en un host remoto.
func SystemdStatus(conn SSHConn, unitName string, logLines int) (SystemdServiceStatus, error) {
	status := SystemdServiceStatus{Unit: unitName}

	// Obtener propiedades del servicio
	cmd := fmt.Sprintf("systemctl show %s --property=ActiveState,SubState,MainPID --no-pager", unitName)
	stdout, stderr, code, err := SSHExec(conn, cmd)
	if err != nil {
		return status, fmt.Errorf("systemd_status: ssh exec: %w", err)
	}
	if code != 0 {
		return status, fmt.Errorf("systemd_status: systemctl show: %s", stderr)
	}

	// Parsear propiedades key=value
	for _, line := range strings.Split(stdout, "\n") {
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			continue
		}
		switch parts[0] {
		case "ActiveState":
			status.Active = parts[1]
		case "SubState":
			status.SubState = parts[1]
		case "MainPID":
			status.MainPID = parts[1]
		}
	}

	// Obtener logs recientes
	if logLines > 0 {
		logCmd := fmt.Sprintf("journalctl -u %s -n %d --no-pager 2>/dev/null || true", unitName, logLines)
		logOut, _, _, logErr := SSHExec(conn, logCmd)
		if logErr == nil {
			status.Logs = strings.TrimSpace(logOut)
		}
	}

	return status, nil
}
