package webagent

import (
	"net/http"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/api/dto/converter"
)

type RuntimeSnapshotRuntime interface {
	MachineConnected(machineID string) bool
	AgentRuntimeRunning(machineID string, agentID string) bool
	AgentRuntimeSessionID(machineID string, agentID string) (string, bool)
}

type RuntimeSnapshotHandler struct {
	store   RuntimeSnapshotStore
	runtime RuntimeSnapshotRuntime
}

// List handles POST /api/agents/runtime-snapshots.
// Returns lightweight runtime state for explicitly requested agents only. The
// request is capped so callers cannot turn the endpoint into a workspace-wide
// agent list.
func (handler *RuntimeSnapshotHandler) List(r api.WorkspaceScopedJSON[dto.AgentRuntimeSnapshotsRequest]) (api.Response, error) {
	if handler.store == nil {
		return api.Response{}, api.ErrNotFound
	}
	agentIDs := normalizeRequestedAgentIDs(r.Body.AgentIDs)
	if len(agentIDs) == 0 {
		return api.OK(dto.AgentRuntimeSnapshotsResponse{Snapshots: []dto.AgentRuntimeSnapshot{}}), nil
	}
	if len(agentIDs) > maxRuntimeSnapshotAgentIDs {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "too many agentIds")
	}

	snapshots, err := handler.store.AgentRuntimeSnapshotsForWorkspace(r.Context(), r.UserID(), r.WorkspaceID(), agentIDs)
	if err != nil {
		return api.Response{}, err
	}
	applyRuntimeSnapshotState(snapshots, handler.runtime, time.Now().UTC())
	return api.OK(dto.AgentRuntimeSnapshotsResponse{
		Snapshots: converter.ToAgentRuntimeSnapshots(snapshots),
	}), nil
}
