package main

import (
	"fmt"
	"log"
	"os"
)

// LogLevel controls verbosity.
type LogLevel int

const (
	LogDebug LogLevel = iota
	LogInfo
	LogSilent
)

// logLevel is set in main() from the --log-level flag.
var logLevel LogLevel = LogInfo

// setLogLevel parses the flag value.
func setLogLevel(val string) {
	switch val {
	case "debug":
		logLevel = LogDebug
	case "info":
		logLevel = LogInfo
	case "silent":
		logLevel = LogSilent
	default:
		log.Fatalf("invalid --log-level %q (want debug, info, or silent)", val)
	}
}

func logDebug(format string, v ...interface{}) {
	if logLevel == LogDebug {
		log.Printf(format, v...)
	}
}

func logInfo(format string, v ...interface{}) {
	if logLevel <= LogInfo {
		log.Printf(format, v...)
	}
}

func logWarn(format string, v ...interface{}) {
	log.Printf(format, v...)
}

func logFatal(format string, v ...interface{}) {
	log.Fatalf(format, v...)
}

// logHTTPRequest logs an HTTP request in debug mode.
func logHTTPRequest(method, url string, statusCode int, duration float64) {
	if logLevel == LogDebug {
		log.Printf("HTTP %s %s -> %d (%.2fs)", method, url, statusCode, duration)
	}
}

// logHTTPRetry logs a retry attempt in debug mode.
func logHTTPRetry(attempt, maxAttempts int, backoffSecs int, target string) {
	if logLevel == LogDebug {
		log.Printf("retry %d/%d for %s after %ds backoff", attempt, maxAttempts, target, backoffSecs)
	}
}

// logFatalErr is like logFatal but takes a message and error separately.
func logFatalErr(msg string, err error) {
	log.Fatalf("%s: %v", msg, err)
}

// Fatal with two args like the original log.Fatal(err, msg) pattern.
func logFatalTwoArgs(err error, msg string) {
	fmt.Fprintln(os.Stderr, err)
	log.Fatalf("%s", msg)
}
