package logging

import (
	"errors"
	"fmt"
	"io"
	"os"
	"regexp"
)

var (
	parsedValuePattern = regexp.MustCompile(`parsing "[^"]*"`)
	secretValuePattern = regexp.MustCompile(`(?i)(token|secret|password|authorization)(=|:)\S+`)
)

// WriteBootstrapError reports failures that happen before the configured
// pipeline exists. It intentionally omits filesystem paths and raw config
// values while retaining the actionable validation or OS reason.
func WriteBootstrapError(writer io.Writer, operation string, err error) {
	if writer == nil || err == nil {
		return
	}
	_, _ = fmt.Fprintf(writer, "agentteam bootstrap: %s: %s\n", operation, safeBootstrapError(err))
}

func safeBootstrapError(err error) string {
	var pathError *os.PathError
	if errors.As(err, &pathError) {
		return fmt.Sprintf("%s: %v", pathError.Op, pathError.Err)
	}
	message := parsedValuePattern.ReplaceAllString(err.Error(), `parsing "<redacted>"`)
	return secretValuePattern.ReplaceAllString(message, `$1$2<redacted>`)
}
