package logging

import (
	"fmt"
	"runtime"
	"strings"
)

const (
	stacktraceMaxFrames = 32
	stacktraceMaxBytes  = 8 * 1024
)

func boundedStacktrace() string {
	pcs := make([]uintptr, stacktraceMaxFrames)
	count := runtime.Callers(5, pcs)
	frames := runtime.CallersFrames(pcs[:count])
	var stack strings.Builder
	stack.Grow(2048)
	for {
		frame, more := frames.Next()
		line := fmt.Sprintf("%s\n\t%s:%d", frame.Function, frame.File, frame.Line)
		if stack.Len()+len(line)+1 > stacktraceMaxBytes {
			break
		}
		if stack.Len() > 0 {
			stack.WriteByte('\n')
		}
		stack.WriteString(line)
		if !more {
			break
		}
	}
	return stack.String()
}
