package stack

import (
	"encoding/json"
	"strings"
)

// parsePsOutput handles both formats emitted by `docker compose ps --format json`:
// newer versions emit NDJSON (one object per line); older versions emit a single JSON array.
func parsePsOutput(out string) []Service {
	out = strings.TrimSpace(out)
	if out == "" {
		return nil
	}

	// Array form.
	if strings.HasPrefix(out, "[") {
		var arr []Service
		if err := json.Unmarshal([]byte(out), &arr); err == nil {
			return arr
		}
	}

	// NDJSON form: one object per line.
	var services []Service
	for _, line := range strings.Split(out, "\n") {
		line = strings.TrimSpace(line)
		if line == "" || !strings.HasPrefix(line, "{") {
			continue
		}
		var svc Service
		if err := json.Unmarshal([]byte(line), &svc); err != nil {
			continue
		}
		services = append(services, svc)
	}
	return services
}
