package restic

import (
	"encoding/json"
	"fmt"
	"strings"
	"time"
)

// Snapshot represents a single restic snapshot as returned by
// `restic snapshots --json`.
type Snapshot struct {
	ID       string    `json:"id"`
	ShortID  string    `json:"short_id"`
	Time     time.Time `json:"time"`
	Hostname string    `json:"hostname"`
	Paths    []string  `json:"paths"`
	Tags     []string  `json:"tags"`
}

// ParseSnapshots decodes the JSON output of `restic snapshots --json`
// into a slice of Snapshot values.
func ParseSnapshots(data []byte) ([]Snapshot, error) {
	var snapshots []Snapshot
	if err := json.Unmarshal(data, &snapshots); err != nil {
		return nil, fmt.Errorf("parsing snapshot JSON: %w", err)
	}
	return snapshots, nil
}

// FormatSnapshotLine returns a single-line human-readable summary of a
// snapshot, suitable for use as a menu option label. The format is:
//
//	<short_id>  <date> <time>  <hostname>  <paths>  [<tags>]
//
// Paths and tags are omitted when empty. Hostname shows "(unknown)"
// when blank.
func FormatSnapshotLine(s Snapshot) string {
	var b strings.Builder

	b.WriteString(s.ShortID)
	b.WriteString("  ")
	b.WriteString(s.Time.Format("2006-01-02 15:04"))

	b.WriteString("  ")
	if s.Hostname == "" {
		b.WriteString("(unknown)")
	} else {
		b.WriteString(s.Hostname)
	}

	if len(s.Paths) > 0 {
		b.WriteString("  ")
		b.WriteString(strings.Join(s.Paths, ", "))
	}

	if len(s.Tags) > 0 {
		b.WriteString("  [")
		b.WriteString(strings.Join(s.Tags, ", "))
		b.WriteString("]")
	}

	return b.String()
}
