package internal

import (
	"fmt"
	"runtime"

	"github.com/charmbracelet/log"
)

func Error(msg string) HelpError {
	caller := ""
	if Debug {
		_, file, line, _ := runtime.Caller(1)
		caller = log.ShortCallerFormatter(file, line, "")

	}
	return HelpError{err: msg, caller: caller}
}

func Errorf(format string, a ...any) HelpError {
	caller := ""
	if Debug {
		_, file, line, _ := runtime.Caller(1)
		caller = log.ShortCallerFormatter(file, line, "")

	}
	return HelpError{err: fmt.Sprintf(format, a...), caller: caller}
}

type HelpError struct {
	err    string
	caller string
	help   string
}

func (e HelpError) Help(help string) HelpError {
	e.help = help
	return e
}

func (e HelpError) Helpf(format string, a ...any) HelpError {
	e.help = fmt.Sprintf(format, a...)
	return e
}

func (e HelpError) Error() string {
	return e.format()
}

func (e HelpError) format() string {
	msg := ""
	if e.caller != "" {
		msg += fmt.Sprintf("<%s> ", e.caller)
	}

	msg += e.err
	if e.help == "" {
		return msg
	}

	return fmt.Sprintf(`%s

Help: %s `, msg, e.help)
}
