package localapi

import (
	"net/http"
	"strconv"
	"time"

	applog "gitea.dooplex.hu/admin/felhom-agent/internal/log"
)

// GET /debug/logs (v0.83.0 observability) — the agent's always-DEBUG capture ring,
// served over the same token-authed, self-scoped local API as every sibling route.
// This is what makes the agent's side of a flow (e.g. a NAS verify) visible from the
// controller's Debug page without journald access or a config flip. ?raw=1 mirrors
// the controller viewer's plain-text variant. Log lines carry keys never values
// (logging conventions), so the ring is safe to serve to the guest's operator view.

// handleDebugLogs serves the ring as JSON entries ({entries, total}) or plain text.
func (s *Server) handleDebugLogs(w http.ResponseWriter, r *http.Request, vmid int) {
	if s.logRing == nil {
		writeErr(w, http.StatusServiceUnavailable, "debug log ring not configured on this agent")
		return
	}
	limit := 0 // 0 = everything held (ring-bounded)
	if v := r.URL.Query().Get("limit"); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= applog.DefaultRingSize {
			limit = n
		}
	}
	if r.URL.Query().Get("raw") == "1" {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		for _, line := range s.logRing.Lines(0) {
			w.Write([]byte(line))
			w.Write([]byte("\n"))
		}
		return
	}
	entries, total := s.logRing.Entries(limit)
	writeOK(w, map[string]any{"vmid": vmid, "entries": entries, "total": total})
}

// statusRecorder captures the wrapped handler's status for the request log line.
type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (sr *statusRecorder) WriteHeader(code int) {
	sr.status = code
	sr.ResponseWriter.WriteHeader(code)
}

// logRequests is the request-level DEBUG middleware: method, path, status, duration
// — never bodies (bodies can carry secrets; the ring must not).
func (s *Server) logRequests(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		s.logger.Debug("local-api: request",
			"method", r.Method, "path", r.URL.Path,
			"status", rec.status, "duration_ms", time.Since(start).Milliseconds())
	})
}
