package check

import (
	"fmt"
	"math"
	"reflect"
	"runtime"
	"strings"
)

// callerFuncName returns the unqualified checker name for the caller
// at the given stack depth, stripping any "(*Receiver)." prefix.
// Checker methods currently live on *checks,
// but strip generically rather than pinning to one receiver type,
// since report0/1/2/3 are also reachable through *TB (Error/Errorf/Fatal/Fatalf)
// and *C (their delegators).
func callerFuncName(stack int) string {
	pc, _, _, _ := runtime.Caller(stack + 1)
	name := funcNameAt(pc)
	if strings.HasPrefix(name, "(*") {
		if i := strings.Index(name, ")."); i != -1 {
			name = name[i+2:]
		}
	}
	return name
}

func funcName(f any) string {
	return funcNameAt(reflect.ValueOf(f).Pointer())
}

func funcNameAt(pc uintptr) string {
	name := "<unknown>"
	if f := runtime.FuncForPC(pc); f != nil {
		name = f.Name()
		if i := strings.LastIndex(name, "/"); i != -1 {
			name = name[i+1:]
		}
		if i := strings.Index(name, "."); i != -1 {
			name = name[i+1:]
		}
	}
	return name
}

func format(msg ...any) string {
	if len(msg) > 1 {
		return fmt.Sprintf(msg[0].(string), msg[1:]...)
	}
	return fmt.Sprint(msg...)
}

// digits return amount of decimal digits in number.
func digits(number int) int {
	if number == 0 {
		return 1
	}
	return int(math.Floor(math.Log10(float64(number)) + 1))
}
