package godump

import (
	
	
	
	
	
	
	
	
	
	
	
)

const (
	colorReset   = "\033[0m"
	colorGray    = "\033[90m"
	colorYellow  = "\033[33m"
	colorRed     = "\033[31m"
	colorGreen   = "\033[32m"
	colorRedBg   = "\033[48;2;34;16;16m"
	colorGreenBg = "\033[48;2;16;34;22m"
	colorLime    = "\033[1;38;5;113m"
	colorCyan    = "\033[38;5;38m"
	colorNote    = "\033[38;5;38m"
	colorRef     = "\033[38;5;247m"
	colorMeta    = "\033[38;5;170m"
	colorDefault = "\033[38;5;208m"
	indentWidth  = 2
)

// Default configuration values for the Dumper.
const (
	defaultDisableStringer = false
	defaultMaxDepth        = 15
	defaultMaxItems        = 100
	defaultMaxStringLen    = 100000
	defaultMaxStackDepth   = 10
	initialCallerSkip      = 2
)

// defaultDumper is the default Dumper instance used by Dump and DumpStr functions.
var defaultDumper = NewDumper()

// exitFunc is a function that can be overridden for testing purposes.
var exitFunc = os.Exit

// Colorizer is a function type that takes a color code and a string, returning the colorized string.
type Colorizer func(code, str string) string

// colorizeUnstyled returns the string without any colorization.
//
// It satisfies the [Colorizer] interface.
func colorizeUnstyled(,  string) string {
	return  // No colorization
}

// colorizeANSI colorizes the string using ANSI escape codes.
//
// It satisfies the [Colorizer] interface.
func colorizeANSI(,  string) string {
	return  +  + colorReset
}

// htmlColorMap maps color codes to HTML colors.
var htmlColorMap = map[string]string{
	colorGray:    "#999",
	colorYellow:  "#ffb400",
	colorRed:     "#ff5f5f",
	colorGreen:   "#55d655",
	colorLime:    "#80ff80",
	colorNote:    "#40c0ff",
	colorRef:     "#aaa",
	colorMeta:    "#d087d0",
	colorDefault: "#ff7f00",
}

// colorizeHTML colorizes the string using HTML span tags.
//
// It satisfies the [Colorizer] interface.
func colorizeHTML(,  string) string {
	return fmt.Sprintf(`<span style="color:%s">%s</span>`, htmlColorMap[], )
}

// Dumper holds configuration for dumping structured data.
// It controls depth, item count, and string length limits.
type Dumper struct {
	maxDepth           int
	maxItems           int
	maxStringLen       int
	writer             io.Writer
	skippedStackFrames int
	disableStringer    bool
	disableColor       bool

	// callerFn is used to get the caller information.
	// It defaults to [runtime.Caller], it is here to be overridden for testing purposes.
	callerFn func(skip int) (uintptr, string, int, bool)

	// colorizer is used to apply color formatting to the output.
	colorizer Colorizer
}

// Option defines a functional option for configuring a Dumper.
type Option func(*Dumper) *Dumper

// dumpState tracks reference ids for a single dump call.
type dumpState struct {
	nextRefID int
	refs      map[uintptr]int
}

// newDumpState initializes per-dump reference tracking.
func newDumpState() *dumpState {
	return &dumpState{
		nextRefID: 1,
		refs:      map[uintptr]int{},
	}
}

// WithMaxDepth limits how deep the structure will be dumped.
// Param n must be 0 or greater or this will be ignored, and default MaxDepth will be 15.
// @group Options
//
// Example: limit depth
//
//	// Default: 15
//	v := map[string]map[string]int{"a": {"b": 1}}
//	d := godump.NewDumper(godump.WithMaxDepth(1))
//	d.Dump(v)
//	// #map[string]int {
//	//   a => #map[string]int {
//	//     b => ... (max depth)
//	//   }
//	// }
func ( int) Option {
	return func( *Dumper) *Dumper {
		if  >= 0 {
			.maxDepth = 
		}
		return 
	}
}

// WithMaxItems limits how many items from an array, slice, or map can be printed.
// Param n must be 0 or greater or this will be ignored, and default MaxItems will be 100.
// @group Options
//
// Example: limit items
//
//	// Default: 100
//	v := []int{1, 2, 3}
//	d := godump.NewDumper(godump.WithMaxItems(2))
//	d.Dump(v)
//	// #[]int [
//	//   0 => 1 #int
//	//   1 => 2 #int
//	//   ... (truncated)
//	// ]
func ( int) Option {
	return func( *Dumper) *Dumper {
		if  >= 0 {
			.maxItems = 
		}
		return 
	}
}

// WithMaxStringLen limits how long printed strings can be.
// Param n must be 0 or greater or this will be ignored, and default MaxStringLen will be 100000.
// @group Options
//
// Example: limit string length
//
//	// Default: 100000
//	v := "hello world"
//	d := godump.NewDumper(godump.WithMaxStringLen(5))
//	d.Dump(v)
//	// "hello…" #string
func ( int) Option {
	return func( *Dumper) *Dumper {
		if  >= 0 {
			.maxStringLen = 
		}
		return 
	}
}

// WithWriter routes output to the provided writer.
// @group Options
//
// Example: write to buffer
//
//	// Default: stdout
//	var b strings.Builder
//	v := map[string]int{"a": 1}
//	d := godump.NewDumper(godump.WithWriter(&b))
//	d.Dump(v)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( io.Writer) Option {
	return func( *Dumper) *Dumper {
		.writer = 
		return 
	}
}

// WithSkipStackFrames skips additional stack frames for header reporting.
// This is useful when godump is wrapped and the actual call site is deeper.
// @group Options
//
// Example: skip wrapper frames
//
//	// Default: 0
//	v := map[string]int{"a": 1}
//	d := godump.NewDumper(godump.WithSkipStackFrames(2))
//	d.Dump(v)
//	// <#dump // ../../../../usr/local/go/src/runtime/asm_arm64.s:1223
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( int) Option {
	return func( *Dumper) *Dumper {
		if  >= 0 {
			.skippedStackFrames = 
		}
		return 
	}
}

// WithDisableStringer disables using the fmt.Stringer output.
// When enabled, the underlying type is rendered instead of String().
// @group Options
//
// Example: show raw types
//
//	// Default: false
//	v := time.Duration(3)
//	d := godump.NewDumper(godump.WithDisableStringer(true))
//	d.Dump(v)
//	// 3 #time.Duration
func ( bool) Option {
	return func( *Dumper) *Dumper {
		.disableStringer = 
		return 
	}
}

// WithoutColor disables colorized output for the dumper.
// @group Options
//
// Example: disable colors
//
//	// Default: false
//	v := map[string]int{"a": 1}
//	d := godump.NewDumper(godump.WithoutColor())
//	d.Dump(v)
//	// (prints without color)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func () Option {
	return func( *Dumper) *Dumper {
		.disableColor = true
		.colorizer = colorizeUnstyled
		return 
	}
}

// NewDumper creates a new Dumper with the given options applied.
// Defaults are used for any setting not overridden.
// @group Builder
//
// Example: build a custom dumper
//
//	v := map[string]int{"a": 1}
//	d := godump.NewDumper(
//		godump.WithMaxDepth(10),
//		godump.WithWriter(os.Stdout),
//	)
//	d.Dump(v)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( ...Option) *Dumper {
	 := &Dumper{
		maxDepth:        defaultMaxDepth,
		maxItems:        defaultMaxItems,
		maxStringLen:    defaultMaxStringLen,
		disableStringer: defaultDisableStringer,
		writer:          os.Stdout,
		colorizer:       nil, // ensure no detection is made if we don't need it
		callerFn:        runtime.Caller,
	}
	for ,  := range  {
		 = ()
	}
	return 
}

// Dump prints the values to stdout with colorized output.
// @group Dump
//
// Example: print to stdout
//
//	v := map[string]int{"a": 1}
//	godump.Dump(v)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( ...any) {
	defaultDumper.Dump(...)
}

// Dump prints the values to stdout with colorized output.
// @group Dump
//
// Example: print with a custom dumper
//
//	d := godump.NewDumper()
//	v := map[string]int{"a": 1}
//	d.Dump(v)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( *Dumper) ( ...any) {
	fmt.Fprint(.writer, .DumpStr(...))
}

// Fdump writes the formatted dump of values to the given io.Writer.
// @group Dump
//
// Example: dump to writer
//
//	var b strings.Builder
//	v := map[string]int{"a": 1}
//	godump.Fdump(&b, v)
//	// outputs to strings builder
func ( io.Writer,  ...any) {
	NewDumper(WithWriter()).Dump(...)
}

// DumpStr returns a string representation of the values with colorized output.
// @group Dump
//
// Example: get a string dump
//
//	v := map[string]int{"a": 1}
//	out := godump.DumpStr(v)
//	godump.Dump(out)
//	// "#map[string]int {\n  a => 1 #int\n}" #string
func ( ...any) string {
	return defaultDumper.DumpStr(...)
}

// DumpStr returns a string representation of the values with colorized output.
// @group Dump
//
// Example: get a string dump with a custom dumper
//
//	d := godump.NewDumper()
//	v := map[string]int{"a": 1}
//	out := d.DumpStr(v)
//	_ = out
//	// "#map[string]int {\n  a => 1 #int\n}" #string
func ( *Dumper) ( ...any) string {
	 := .clone()
	 := newDumpState()
	var  strings.Builder
	.printDumpHeader(&)
	 := tabwriter.NewWriter(&, 0, 0, 1, ' ', 0)
	.writeDump(, , ...)
	.Flush()
	return .String()
}

// DumpJSONStr pretty-prints values as JSON and returns it as a string.
// @group JSON
//
// Example: dump JSON string
//
//	v := map[string]int{"a": 1}
//	d := godump.NewDumper()
//	out := d.DumpJSONStr(v)
//	_ = out
//	// {"a":1}
func ( *Dumper) ( ...any) string {
	if len() == 0 {
		return `{"error": "DumpJSON called with no arguments"}`
	}

	var  any = 
	if len() == 1 {
		 = [0]
	}

	,  := json.MarshalIndent(, "", strings.Repeat(" ", indentWidth))
	if  != nil {
		//nolint:errchkjson // fallback handles this manually below
		,  := json.Marshal(map[string]string{"error": .Error()})
		return string()
	}
	return string()
}

// DumpJSON prints a pretty-printed JSON string to the configured writer.
// @group JSON
//
// Example: print JSON
//
//	v := map[string]int{"a": 1}
//	d := godump.NewDumper()
//	d.DumpJSON(v)
//	// {
//	//   "a": 1
//	// }
func ( *Dumper) ( ...any) {
	 := .DumpJSONStr(...)
	fmt.Fprintln(.writer, )
}

// DumpHTML dumps the values as HTML with colorized output.
// @group HTML
//
// Example: dump HTML
//
//	v := map[string]int{"a": 1}
//	html := godump.DumpHTML(v)
//	_ = html
//	// (html output)
func ( ...any) string {
	return defaultDumper.DumpHTML(...)
}

// DumpHTML dumps the values as HTML with colorized output.
// @group HTML
//
// Example: dump HTML with a custom dumper
//
//	d := godump.NewDumper()
//	v := map[string]int{"a": 1}
//	html := d.DumpHTML(v)
//	_ = html
//	fmt.Println(html)
//	// (html output)
func ( *Dumper) ( ...any) string {
	var  strings.Builder
	.WriteString(`<div style='background-color:black;'><pre style="background-color:black; color:white; padding:5px; border-radius: 5px">` + "\n")

	 := .clone()
	if !.disableColor {
		.colorizer = colorizeHTML // use HTML colorizer
	}

	.WriteString(.DumpStr(...))

	.WriteString("</pre></div>")
	return .String()
}

// DumpJSON dumps the values as a pretty-printed JSON string.
// If there is more than one value, they are dumped as a JSON array.
// It returns an error string if marshaling fails.
// @group JSON
//
// Example: print JSON
//
//	v := map[string]int{"a": 1}
//	godump.DumpJSON(v)
//	// {
//	//   "a": 1
//	// }
func ( ...any) {
	defaultDumper.DumpJSON(...)
}

// DumpJSONStr dumps the values as a JSON string.
// @group JSON
//
// Example: JSON string
//
//	v := map[string]int{"a": 1}
//	out := godump.DumpJSONStr(v)
//	_ = out
//	// {"a":1}
func ( ...any) string {
	return defaultDumper.DumpJSONStr(...)
}

// Dd is a debug function that prints the values and exits the program.
// @group Dump
//
// Example: dump and exit
//
//	v := map[string]int{"a": 1}
//	godump.Dd(v)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( ...any) {
	defaultDumper.Dd(...)
}

// Dd is a debug function that prints the values and exits the program.
// @group Debug
//
// Example: dump and exit with a custom dumper
//
//	d := godump.NewDumper()
//	v := map[string]int{"a": 1}
//	d.Dd(v)
//	// #map[string]int {
//	//   a => 1 #int
//	// }
func ( *Dumper) ( ...any) {
	.Dump(...)
	exitFunc(1)
}

// clone creates a copy of the [Dumper] with the same configuration.
// This is useful for creating a new dumper with the same settings without modifying the original.
func ( *Dumper) () *Dumper {
	 := *
	return &
}

// colorize applies the configured [Colorizer] to the string with the given color code.
func ( *Dumper) (,  string) string {
	if .colorizer == nil {
		// this avoids detecting color if not needed
		if .disableColor {
			.colorizer = colorizeUnstyled
			return .colorizer(, )
		}
		.colorizer = newColorizer()
	}
	return .colorizer(, )
}

// ensureColorizer initializes the colorizer when none is configured.
func ( *Dumper) () {
	if .colorizer == nil {
		if .disableColor {
			.colorizer = colorizeUnstyled
			return
		}
		.colorizer = newColorizer()
	}
}

// printDumpHeader prints the header for the dump output, including the file and line number.
func ( *Dumper) ( io.Writer) {
	,  := .findFirstNonInternalFrame(.skippedStackFrames)
	if  == "" {
		return
	}

	 := 
	if ,  := os.Getwd();  == nil {
		if ,  := filepath.Rel(, );  == nil {
			 = 
		}
	}

	 := fmt.Sprintf("<#dump // %s:%d", , )
	fmt.Fprintln(, .colorize(colorGray, ))
}

// findFirstNonInternalFrame iterates through the call stack to find the first non-internal frame.
func ( *Dumper) ( int) (string, int) {
	for  := initialCallerSkip;  < defaultMaxStackDepth; ++ {
		, , ,  := .callerFn()
		if ! {
			break
		}
		 := runtime.FuncForPC()
		if  == nil || !strings.Contains(.Name(), "godump") || strings.HasSuffix(, "_test.go") {
			if  > 0 {
				--
				continue
			}

			return , 
		}
	}
	return "", 0
}

// formatByteSliceAsHexDump formats a byte slice as a hex dump with ASCII representation.
func ( *Dumper) ( []byte,  int) string {
	var  strings.Builder

	const  = 16
	const  = 50
	const  = 16

	 := strings.Repeat(" ", *indentWidth)
	 := 

	// Header
	.WriteString(fmt.Sprintf("([]uint8) (len=%d cap=%d) {\n", len(), cap()))

	for  := 0;  < len();  +=  {

		 :=  + 
		if  > len() {
			 = len()
		}
		 := [:]

		 := 0

		// Offset
		 := fmt.Sprintf("%08x  ", )
		.WriteString()
		.WriteString(.colorize(colorMeta, ))
		 += len()

		// Hex bytes
		for  := 0;  < ; ++ {
			var  string
			if  < len() {
				 = fmt.Sprintf("%02x ", [])
			} else {
				 = "   "
			}
			if  == 7 {
				 += " "
			}
			.WriteString(.colorize(colorCyan, ))
			 += len()
		}

		// Padding before ASCII
		 :=  - 
		if  < 1 {
			 = 1
		}
		.WriteString(strings.Repeat(" ", ))

		// ASCII section
		.WriteString(.colorize(colorGray, "| "))
		 := 0
		for ,  := range  {
			 := "."
			if  >= 32 &&  <= 126 {
				 = string()
			}
			.WriteString(.colorize(colorLime, ))
			++
		}
		if  <  {
			.WriteString(strings.Repeat(" ", -))
		}
		.WriteString(.colorize(colorGray, " |") + "\n")
	}

	// Closing
	 = [:len()-indentWidth]
	.WriteString( + "}")
	return .String()
}

func ( *Dumper) ( io.Writer,  *dumpState,  ...any) {
	for ,  := range  {
		 := reflect.ValueOf()
		 = makeAddressable()
		.printValue(, , 0, )
		fmt.Fprintln()
	}
}

func ( *Dumper) ( reflect.Type) string {
	switch .Kind() {
	case reflect.Map:
		return fmt.Sprintf("map[%s]%s", .(.Key()), .(.Elem()))
	case reflect.Slice:
		return fmt.Sprintf("[]%s", .(.Elem()))
	case reflect.Array:
		return fmt.Sprintf("[%d]%s", .Len(), .(.Elem()))
	case reflect.Ptr:
		return fmt.Sprintf("*%s", .(.Elem()))
	default:
		return .String()
	}
}

func ( *Dumper) ( io.Writer,  reflect.Value,  int,  *dumpState) {
	if  > .maxDepth {
		fmt.Fprint(, .colorize(colorGray, "... (max depth)"))
		return
	}
	if !.IsValid() {
		fmt.Fprint(, .colorize(colorGray, "<invalid>"))
		return
	}

	if  := .asStringer();  != "" {
		fmt.Fprint(, )
		return
	}

	switch .Kind() {
	case reflect.Chan:
		 := .colorizer(colorGray, .getTypeString(.Type()))

		if .IsNil() {
			fmt.Fprint(, .colorize(colorGray, fmt.Sprintf("#%s(nil)", )))
		} else {
			fmt.Fprintf(, "%s(%s)", .colorize(colorGray, ), .colorize(colorCyan, fmt.Sprintf("%#x", .Pointer())))
		}
		return
	}

	if isNil() {
		 := .getTypeString(.Type())
		fmt.Fprintf(, .colorize(colorLime, )+.colorize(colorGray, "(nil)"))
		return
	}

	if .Kind() == reflect.Ptr && .CanAddr() {
		 := .Pointer()
		if ,  := .refs[];  {
			fmt.Fprintf(, .colorize(colorRef, "↩︎ &%d"), )
			return
		} else {
			.refs[] = .nextRefID
			.nextRefID++
		}
	}

	// We don't need to check any previous checks (validity, channel, nil,
	// addressable pointer) since they all work directly on the pointer type. We
	// can simply continue with the reference value from here and add a pointer
	// prefix to the output.
	 := ""
	for .Kind() == reflect.Ptr {
		 += "*"
		 = .Elem()
	}

	switch .Kind() {
	case reflect.Interface:
		.(, .Elem(), , )
	case reflect.Struct:
		 := .Type()
		fmt.Fprintf(, "%s {", .colorize(colorGray, fmt.Sprintf("#%s%s", , .getTypeString(.Type()))))
		fmt.Fprintln()

		for  := 0;  < .NumField(); ++ {
			 := .Field()
			 := .Field()

			 := "+"
			if .PkgPath != "" {
				 = "-"
				 = forceExported()
			}
			indentPrint(, +1, .colorize(colorYellow, )+.Name)
			fmt.Fprint(, "	=> ")
			if  := .asStringer();  != "" {
				fmt.Fprint(, )
			} else {
				.(, , +1, )
			}
			fmt.Fprintln()
		}
		indentPrint(, , "")
		fmt.Fprint(, "}")
	case reflect.Complex64, reflect.Complex128:
		fmt.Fprint(, .colorize(colorCyan, fmt.Sprintf("%v", .Complex())))
	case reflect.UnsafePointer:
		fmt.Fprint(, .colorize(colorGray, fmt.Sprintf("unsafe.Pointer(%#x)", .Pointer())))
	case reflect.Map:
		fmt.Fprintf(, "%s {", .colorize(colorGray, fmt.Sprintf("#%s%s", , .getTypeString(.Type()))))
		fmt.Fprintln()

		 := .MapKeys()
		for ,  := range  {
			if  >= .maxItems {
				indentPrint(, +1, .colorize(colorGray, "... (truncated)"))
				break
			}
			 := fmt.Sprintf("%v", .Interface())
			indentPrint(, +1, fmt.Sprintf(" %s => ", .colorize(colorMeta, )))
			.(, .MapIndex(), +1, )
			fmt.Fprintln()
		}
		indentPrint(, , "")
		fmt.Fprint(, "}")
	case reflect.Slice, reflect.Array:
		// []byte handling
		if .Type().Elem().Kind() == reflect.Uint8 {
			if .CanConvert(reflect.TypeOf([]byte{})) { // Check if it can be converted to []byte
				if ,  := .Convert(reflect.TypeOf([]byte{})).Interface().([]byte);  {
					 := .formatByteSliceAsHexDump(, +1)
					fmt.Fprint(, .colorize(colorLime, ))
					break
				}
			}
		}

		// Default rendering for other slices/arrays
		fmt.Fprintf(, "%s [", .colorize(colorGray, fmt.Sprintf("#%s%s", , .getTypeString(.Type()))))
		fmt.Fprintln()

		for  := 0;  < .Len(); ++ {
			if  >= .maxItems {
				indentPrint(, +1, .colorize(colorGray, "... (truncated)\n"))
				break
			}
			indentPrint(, +1, fmt.Sprintf("%s => ", .colorize(colorCyan, fmt.Sprintf("%d", ))))
			.(, .Index(), +1, )
			fmt.Fprintln()
		}
		indentPrint(, , "")
		fmt.Fprint(, "]")
	case reflect.String:
		 := escapeControl(.String())
		if utf8.RuneCountInString() > .maxStringLen {
			 := []rune()
			 = string([:.maxStringLen]) + "…"
		}
		fmt.Fprint(, .colorize(colorYellow, `"`)+.colorize(colorLime, )+.colorize(colorYellow, `"`))
	case reflect.Bool:
		if .Bool() {
			fmt.Fprint(, .colorize(colorYellow, "true"))
		} else {
			fmt.Fprint(, .colorize(colorGray, "false"))
		}
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		fmt.Fprint(, .colorize(colorCyan, fmt.Sprint(.Int())))
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		fmt.Fprint(, .colorize(colorCyan, fmt.Sprint(.Uint())))
	case reflect.Float32, reflect.Float64:
		fmt.Fprint(, .colorize(colorCyan, fmt.Sprintf("%f", .Float())))
	case reflect.Func:
		fmt.Fprint(, .colorize(colorGray, .Type().String()))
	}

	// These types should not have post types since they have a body and already
	// had their type written out.
	if contains([]reflect.Kind{
		reflect.Struct,
		reflect.UnsafePointer,
		reflect.Map,
		reflect.Slice,
		reflect.Array,
		reflect.Ptr,
		reflect.Interface,
	}, .Kind()) {
		return
	}

	fmt.Fprint(, .colorizer(colorGray, fmt.Sprintf(" #%s%s", , .getTypeString(.Type()))))
}

// asStringer checks if the value implements fmt.Stringer and returns its string representation.
func ( *Dumper) ( reflect.Value) string {
	if .disableStringer {
		return ""
	}

	 := 
	if !.CanInterface() {
		 = forceExported()
	}
	if .CanInterface() {
		if ,  := .Interface().(fmt.Stringer);  {
			 := reflect.ValueOf()
			if .Kind() == reflect.Ptr && .IsNil() {
				return .colorize(colorGray, .Type().String()+"(nil)")
			}
			return .colorize(colorLime, .String()) + .colorize(colorGray, " #"+.getTypeString(.Type()))
		}
	}
	return ""
}

// indentPrint prints indented text to the writer.
func indentPrint( io.Writer,  int,  string) {
	fmt.Fprint(, strings.Repeat(" ", *indentWidth)+)
}

// forceExported returns a value that is guaranteed to be exported, even if it is unexported.
func forceExported( reflect.Value) reflect.Value {
	if .CanInterface() {
		return 
	}
	if .CanAddr() {
		return reflect.NewAt(.Type(), unsafe.Pointer(.UnsafeAddr())).Elem()
	}
	// Final fallback: return original value, even if unexported
	return 
}

// makeAddressable ensures the value is addressable, wrapping structs in pointers if necessary.
func makeAddressable( reflect.Value) reflect.Value {
	// Already addressable? Do nothing
	if .CanAddr() {
		return 
	}

	// If it's a struct and not addressable, wrap it in a pointer
	if .Kind() == reflect.Struct {
		 := reflect.New(.Type())
		.Elem().Set()
		return .Elem()
	}

	return 
}

// isNil checks if the value is nil based on its kind.
func isNil( reflect.Value) bool {
	switch .Kind() {
	case reflect.Ptr, reflect.Slice, reflect.Map, reflect.Interface, reflect.Func, reflect.Chan:
		return .IsNil()
	default:
		return false
	}
}

// replacer is used to escape control characters in strings.
var replacer = strings.NewReplacer(
	"\n", `\n`,
	"\t", `\t`,
	"\r", `\r`,
	"\v", `\v`,
	"\f", `\f`,
	"\x1b", `\x1b`,
)

// escapeControl escapes control characters in a string for safe display.
func escapeControl( string) string {
	return replacer.Replace()
}

// detectColor checks environment variables to determine if color output should be enabled.
func detectColor() bool {
	if os.Getenv("NO_COLOR") != "" {
		return false
	}
	if os.Getenv("FORCE_COLOR") != "" {
		return true
	}
	return true
}

func newColorizer() Colorizer {
	if detectColor() {
		return colorizeANSI
	}
	return colorizeUnstyled
}

func contains( []reflect.Kind,  reflect.Kind) bool {
	for ,  := range  {
		if  ==  {
			return true
		}
	}

	return false
}