package dashboard

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/desktop/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/desktop/internal/profile"
)

// OverviewHandler handles dashboard overview requests.
type OverviewHandler struct{}

// NewOverviewHandler creates a new OverviewHandler.
func NewOverviewHandler() gin.HandlerFunc {
	return (&OverviewHandler{}).Handle
}

// Handle returns summary information for the dashboard home page.
func (h *OverviewHandler) Handle(c *gin.Context) {
	c.JSON(http.StatusOK, BuildOverview())
}

// BuildOverview assembles the dashboard overview payload. It is exported
// so bundle endpoints can embed it without re-implementing the logic.
func BuildOverview() dto.OverviewResponse {
	mgr := profile.Default()
	profiles := mgr.Agents().All()
	runtimes := mgr.Runtimes().All()
	servers := mgr.Servers().All()
	cfg := mgr.Config()

	resp := dto.OverviewResponse{
		Server: dto.OverviewServer{
			Host:    cfg.Host,
			Port:    cfg.Port,
			Address: cfg.Host + ":" + strconv.Itoa(cfg.Port),
		},
		Servers: make([]dto.OverviewServerConfig, 0, len(servers)),
	}

	resp.Summary.AgentCount = len(profiles)

	resp.Summary.RuntimeCount = len(runtimes)
	resp.Summary.EnabledRuntimeCount = len(runtimes)

	resp.Summary.SkillCount = len(mgr.Skills().All())

	resp.Summary.ServerCount = len(servers)
	for _, server := range servers {
		if server.Enabled {
			resp.Summary.EnabledServerCount++
		}

		resp.Servers = append(resp.Servers, dto.OverviewServerConfig{
			ID:      server.ID,
			Enabled: server.Enabled,
		})
	}

	return resp
}
