package infra

import (
	"fmt"
	"sort"
	"strings"
)

// SSHConfigRender convierte una lista de SSHConfigEntry al formato texto
// de ~/.ssh/config. Cada bloque se separa con una linea en blanco.
func SSHConfigRender(entries []SSHConfigEntry) string {
	var sb strings.Builder
	for i, e := range entries {
		if i > 0 {
			sb.WriteString("\n")
		}
		sb.WriteString(fmt.Sprintf("Host %s\n", e.Alias))
		if e.HostName != "" {
			sb.WriteString(fmt.Sprintf("    HostName %s\n", e.HostName))
		}
		if e.User != "" {
			sb.WriteString(fmt.Sprintf("    User %s\n", e.User))
		}
		if e.Port != 0 {
			sb.WriteString(fmt.Sprintf("    Port %d\n", e.Port))
		}
		if e.IdentityFile != "" {
			sb.WriteString(fmt.Sprintf("    IdentityFile %s\n", e.IdentityFile))
		}
		if len(e.Options) > 0 {
			keys := make([]string, 0, len(e.Options))
			for k := range e.Options {
				keys = append(keys, k)
			}
			sort.Strings(keys)
			for _, k := range keys {
				sb.WriteString(fmt.Sprintf("    %s %s\n", k, e.Options[k]))
			}
		}
	}
	return sb.String()
}
