package logging

import (
	"log/slog"
	"os"
	"strings"
)

// Config holds logging configuration
type Config struct {
	Level    string `yaml:"level"`
	File     string `yaml:"file"`
	AuditLog string `yaml:"audit_log"`
}

// LevelFromEnv reads LOG_LEVEL (if set) and returns the matching slog level.
// Accepted values: debug, info, warn, error. Defaults to info.
func LevelFromEnv() slog.Level {
	return parseLevel(os.Getenv("LOG_LEVEL"), slog.LevelInfo)
}

func parseLevel(value string, defaultLevel slog.Level) slog.Level {
	switch strings.ToLower(strings.TrimSpace(value)) {
	case "debug":
		return slog.LevelDebug
	case "warn", "warning":
		return slog.LevelWarn
	case "error":
		return slog.LevelError
	case "info", "":
		return slog.LevelInfo
	default:
		return defaultLevel
	}
}

// NewConfiguredLogger creates a logger using the level configured via LOG_LEVEL.
// JSON/text output is still controlled by LOG_FORMAT in NewLogger.
func NewConfiguredLogger() *Logger {
	return NewLogger(LevelFromEnv(), false)
}

// NewLoggerFromConfig creates a logger from configuration
func NewLoggerFromConfig(cfg Config) *Logger {
	level := parseLevel(cfg.Level, slog.LevelInfo)

	if cfg.File != "" {
		return NewFileLogger(level, false, cfg.File)
	}

	return NewLogger(level, false)
}
