package main

// Logging. The agent writes one line per log record to stderr, which systemd hands to journald.
// Under systemd (JOURNAL_STREAM is set) each line starts with a syslog priority, "<3>" for errors,
// "<4>" for warnings, "<6>" for information, so `journalctl -u approvalens-agent -p warning`
// works, and carries no timestamp (journald adds its own). The rest is logfmt:
//
//	level=warn msg="report not delivered, kept in the spool" queued=3 err="HTTP 503"

import (
	"bytes"
	"context"
	"io"
	"log/slog"
	"os"
	"strconv"
	"sync"
	"time"
	"unicode"
)

type logHandler struct {
	mu      *sync.Mutex
	w       io.Writer
	journal bool
	min     slog.Level
	attrs   []slog.Attr
}

func newLogger(w io.Writer, journal bool, min slog.Level) *slog.Logger {
	return slog.New(&logHandler{mu: &sync.Mutex{}, w: w, journal: journal, min: min})
}

// setupLogging installs the default logger: journald format under systemd, plain timestamps otherwise.
func setupLogging() {
	_, underSystemd := os.LookupEnv("JOURNAL_STREAM")
	min := slog.LevelInfo
	if os.Getenv("APPROVALENS_AGENT_DEBUG") == "1" {
		min = slog.LevelDebug
	}
	slog.SetDefault(newLogger(os.Stderr, underSystemd, min))
}

func (h *logHandler) Enabled(_ context.Context, l slog.Level) bool { return l >= h.min }

func (h *logHandler) WithAttrs(as []slog.Attr) slog.Handler {
	c := *h
	c.attrs = append(append([]slog.Attr(nil), h.attrs...), as...)
	return &c
}

func (h *logHandler) WithGroup(string) slog.Handler { return h } // groups are not used

func (h *logHandler) Handle(_ context.Context, r slog.Record) error {
	var b bytes.Buffer
	if h.journal {
		b.WriteString(syslogPrefix(r.Level))
	} else {
		b.WriteString(r.Time.UTC().Format(time.RFC3339))
		b.WriteByte(' ')
	}
	b.WriteString("level=")
	b.WriteString(levelName(r.Level))
	b.WriteString(" msg=")
	b.WriteString(logValue(r.Message))
	for _, a := range h.attrs {
		writeAttr(&b, a)
	}
	r.Attrs(func(a slog.Attr) bool {
		writeAttr(&b, a)
		return true
	})
	b.WriteByte('\n')
	h.mu.Lock()
	defer h.mu.Unlock()
	_, err := h.w.Write(b.Bytes())
	return err
}

func writeAttr(b *bytes.Buffer, a slog.Attr) {
	if a.Key == "" {
		return
	}
	b.WriteByte(' ')
	b.WriteString(a.Key)
	b.WriteByte('=')
	b.WriteString(logValue(a.Value.Resolve().String()))
}

func syslogPrefix(l slog.Level) string {
	switch {
	case l >= slog.LevelError:
		return "<3>"
	case l >= slog.LevelWarn:
		return "<4>"
	case l >= slog.LevelInfo:
		return "<6>"
	default:
		return "<7>"
	}
}

func levelName(l slog.Level) string {
	switch {
	case l >= slog.LevelError:
		return "error"
	case l >= slog.LevelWarn:
		return "warn"
	case l >= slog.LevelInfo:
		return "info"
	default:
		return "debug"
	}
}

// logValue quotes a value when it has spaces, quotes, '=' or control characters (one record is
// always one line), and cuts it to 2000 bytes.
func logValue(s string) string {
	s = truncate(s, 2000)
	if s == "" {
		return `""`
	}
	for _, r := range s {
		if r <= ' ' || r == '"' || r == '=' || r == '\\' || unicode.IsControl(r) || r == 0x7f {
			return strconv.Quote(s)
		}
	}
	return s
}

// logLimited logs a record at most once per `every` for a given key, so a server that stays
// offline for a day does not fill the journal with the same line.
var (
	limitedMu   sync.Mutex
	limitedLast = map[string]time.Time{}
)

func logLimited(key string, every time.Duration, level slog.Level, msg string, args ...any) {
	limitedMu.Lock()
	last, seen := limitedLast[key]
	now := time.Now()
	if seen && now.Sub(last) < every {
		limitedMu.Unlock()
		return
	}
	if len(limitedLast) > 1000 {
		limitedLast = map[string]time.Time{}
	}
	limitedLast[key] = now
	limitedMu.Unlock()
	slog.Log(context.Background(), level, msg, args...)
}
