package infra

import (
	"encoding/json"
	"fmt"
	"os/exec"
)

// DockerListImages lista las imágenes Docker locales.
func DockerListImages() ([]ImageInfo, error) {
	out, err := exec.Command("docker", "images", "--format", "{{json .}}", "--no-trunc").Output()
	if err != nil {
		return nil, fmt.Errorf("docker images: %w", err)
	}

	if len(out) == 0 {
		return nil, nil
	}

	var images []ImageInfo
	for _, line := range splitLines(out) {
		if len(line) == 0 {
			continue
		}
		var raw struct {
			ID         string `json:"ID"`
			Repository string `json:"Repository"`
			Tag        string `json:"Tag"`
			Size       string `json:"Size"`
			Created    string `json:"CreatedAt"`
		}
		if err := json.Unmarshal(line, &raw); err != nil {
			continue
		}
		images = append(images, ImageInfo{
			ID:         raw.ID,
			Repository: raw.Repository,
			Tag:        raw.Tag,
			Size:       raw.Size,
			Created:    raw.Created,
		})
	}

	return images, nil
}
