package tui

import "strings"

// NormalizeTerminalOutput strips ANSI codes, normalizes line endings,
// and removes non-printable control characters from terminal output.
func NormalizeTerminalOutput(s string) string {
	if s == "" {
		return ""
	}

	clean := StripANSI(s)
	clean = strings.ReplaceAll(clean, "\r\n", "\n")
	clean = strings.ReplaceAll(clean, "\r", "\n")

	var b strings.Builder
	b.Grow(len(clean))
	for _, r := range clean {
		switch {
		case r == '\n' || r == '\t':
			b.WriteRune(r)
		case r >= 32 && r != 127:
			b.WriteRune(r)
		}
	}

	return b.String()
}
