package web

import "io"

// LevelFilterWriter drops log lines BELOW a minimum level from the wrapped writer.
// It is the stdout half of the v0.116.0 capture layer: the logger now always fans
// out to (stdout-filter, LogBuffer ring) — the ring captures EVERYTHING (DEBUG
// included) for remote diagnostics, while docker logs keep respecting
// logging.level exactly as before. Lines with no recognizable [LEVEL] tag parse
// as INFO (parseLine), so untagged output keeps flowing at the info level.
type LevelFilterWriter struct {
	w   io.Writer
	min int
}

// NewLevelFilterWriter wraps w so only lines at/above minLevel pass ("debug"
// passes everything; unknown falls back to debug = pass-through).
func NewLevelFilterWriter(w io.Writer, minLevel string) *LevelFilterWriter {
	return &LevelFilterWriter{w: w, min: levelPriority(minLevel)}
}

// Write parses the line's level tag and forwards it only when it clears the
// minimum. It always reports the full length as written (a dropped line is a
// success, not an error — log.Logger must never see a short write).
func (f *LevelFilterWriter) Write(p []byte) (int, error) {
	entry := parseLine(string(p))
	if levelPriority(entry.Level) < f.min {
		return len(p), nil
	}
	if _, err := f.w.Write(p); err != nil {
		return 0, err
	}
	return len(p), nil
}
