// Package logutil provides ANSI-coloured logging helpers shared between the
// job scheduler and the HTTP request logger. Both use the same colour scheme
// and duration formatting so log output is consistent across components.
package logutil

import (
	"fmt"
	"os"
	"time"
)

// noColor controls whether ANSI escape codes are emitted.
// Set via the standard NO_COLOR environment variable (https://no-color.org).
var noColor bool

func init() {
	_, noColor = os.LookupEnv("NO_COLOR")
}

// color returns the escape sequence when NO_COLOR is unset, empty otherwise.
func color(seq string) string {
	if noColor {
		return ""
	}
	return seq
}

// Reset, Bold, Dim — ANSI escape codes for log formatting.
// They are empty strings when NO_COLOR is set.
var (
	Reset   = color("\033[0m")
	Bold    = color("\033[1m")
	Dim     = color("\033[2m")
	Cyan    = color("\033[36m")
	Green   = color("\033[32m")
	Red     = color("\033[31m")
	Yellow  = color("\033[33m")
	Magenta = color("\033[35m")

	BoldGreen   = color("\033[32;1m")
	BoldYellow  = color("\033[33;1m")
	BoldRed     = color("\033[31;1m")
	BoldBlue    = color("\033[34;1m")
	BoldMagenta = color("\033[35;1m")
)

var (
	DebugLvl = Cyan + "[DEBUG]" + Reset
	WarnLvl  = Yellow + "[WARN] " + Reset
	ErrorLvl = Red + "[ERROR]" + Reset
)

func ColoredDuration(d time.Duration) string {
	switch {
	case d < 500*time.Millisecond:
		return Green + d.String() + Reset
	case d < 5*time.Second:
		return Yellow + d.String() + Reset
	default:
		return Red + d.String() + Reset
	}
}

func ColoredRows(n int) string {
	text := fmt.Sprintf("%d row", n)
	if n != 1 {
		text += "s"
	}
	return BoldBlue + text + Reset
}
