package handler

import (
	"encoding/json"
	"net/http"
	"os/exec"

	"mkiso-server/internal/config"
	"mkiso-server/pkg/dicom"
)

// Health returns a handler that checks and reports the status of
// all external dependencies.
func Health(cfg *config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		deps := []struct {
			Name   string `json:"name"`
			Path   string `json:"path"`
			Status string `json:"status"`
		}{
			{"storescp", cfg.DCMTK.Storescp, ""},
			{"movescu", cfg.DCMTK.Movescu, ""},
			{"storescu", cfg.DCMTK.Storescu, ""},
		}

		allOK := true
		for i, dep := range deps {
			if dep.Path == "" {
				deps[i].Status = "not configured"
				allOK = false
				continue
			}
			if dicom.FileExists(dep.Path) {
				// Quick check: can we execute it?
				cmd := exec.Command(dep.Path, "--version")
				if err := cmd.Run(); err == nil {
					deps[i].Status = "ok"
				} else {
					deps[i].Status = "executable not found"
					allOK = false
				}
			} else {
				deps[i].Status = "file not found"
				allOK = false
			}
		}

		// Check microdicom path
		microdicomOK := dicom.DirExists(cfg.ISO.MicrodicomPath)

		response := map[string]interface{}{
			"status":            "ok",
			"dependencies":      deps,
			"microdicom_path":   cfg.ISO.MicrodicomPath,
			"microdicom_exists": microdicomOK,
			"auth_enabled":      cfg.Auth.Enabled,
		}

		statusCode := http.StatusOK
		if !allOK {
			response["status"] = "degraded"
			statusCode = http.StatusOK // still return 200, status field indicates degraded
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(statusCode)
		json.NewEncoder(w).Encode(response)
	}
}
