package httpapi import ( "encoding/json" "net/http" "mfd-monitor-agent/internal/status" ) // Provider supplies the latest cached HostStatus to HTTP handlers. type Provider interface { // Get returns the latest snapshot and whether a snapshot is ready. Get() (status.HostStatus, bool) } // StaticProvider is a test provider with a fixed snapshot response. type StaticProvider struct { Snapshot status.HostStatus OK bool } // Get returns the configured static snapshot and readiness flag. func (p StaticProvider) Get() (status.HostStatus, bool) { return p.Snapshot, p.OK } // New creates the HTTP API handler for health and status endpoints. func New(provider Provider) http.Handler { mux := http.NewServeMux() mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } snapshot, ok := provider.Get() if !ok { writeJSON(w, http.StatusServiceUnavailable, map[string]any{ "status": "starting", }) return } writeJSON(w, http.StatusOK, map[string]any{ "status": "ok", "version": snapshot.Agent.Version, "snapshot_at": snapshot.Agent.SnapshotAt, "snapshot_status": snapshot.Agent.SnapshotStatus, }) }) mux.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } snapshot, ok := provider.Get() if !ok { http.Error(w, "snapshot not ready", http.StatusServiceUnavailable) return } writeJSON(w, http.StatusOK, snapshot) }) return mux } // writeJSON serializes value as JSON with a response status code. func writeJSON(w http.ResponseWriter, code int, value any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(value) }