package webagent

import (
	"net/http"
	"strings"

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

// List handles GET /api/agents/:agentId/workspace-files.
// Lists files in the agent workspace directory.
func (handler *WorkspaceFileHandler) List(r api.WorkspaceScopedRequest) (api.Response, error) {
	agentID := strings.TrimSpace(r.Gin.Param("agentId"))
	if agentID == "" {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "agentId is required")
	}

	agent, err := handler.agentStore.GetAgentWorkspaceReaderForUser(r.Context(), r.UserID(), r.WorkspaceID(), agentID)

	if err != nil {
		return api.Response{}, err
	}

	if handler.runtime == nil {
		return api.Response{}, api.NewHTTPError(http.StatusServiceUnavailable, "Machine is offline")
	}

	dirPath := strings.TrimSpace(r.Gin.Query("dirPath"))
	requestCtx := runtimecontrol.WithRemoteRequestContext(r.Context(), runtimecontrol.RemoteRequestContext{
		Origin: runtimecontrol.RemoteRequestOriginUserInteractive,
		Cause:  runtimecontrol.RemoteRequestCauseWebAPI,
	})
	page, err := handler.runtime.ListAgentWorkspacePage(requestCtx, agent.MachineID, agent.AgentID, dirPath, workspaceListOptions(r.Gin))
	if err != nil {
		return api.Response{}, err
	}

	return api.OK(workspaceFilesPageResponse(page)), nil
}

// Read handles GET /api/agents/:agentId/workspace-files/read.
// Reads the content of a single file from the agent workspace.
func (handler *WorkspaceFileHandler) Read(r api.WorkspaceScopedRequest) (api.Response, error) {
	agentID := strings.TrimSpace(r.Gin.Param("agentId"))
	if agentID == "" {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "agentId is required")
	}

	path := strings.TrimSpace(r.Gin.Query("path"))
	if path == "" {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "path is required")
	}

	agent, err := handler.agentStore.GetAgentForUser(r.Context(), r.UserID(), r.WorkspaceID(), agentID)

	if err != nil {
		return api.Response{}, err
	}

	if handler.runtime == nil {
		return api.Response{}, api.NewHTTPError(http.StatusServiceUnavailable, "Machine is offline")
	}

	requestCtx := runtimecontrol.WithRemoteRequestContext(r.Context(), runtimecontrol.RemoteRequestContext{
		Origin: runtimecontrol.RemoteRequestOriginUserInteractive,
		Cause:  runtimecontrol.RemoteRequestCauseWebAPI,
	})
	content, err := handler.runtime.ReadAgentWorkspaceFile(requestCtx, agent.MachineID, agent.AgentID, path)
	if err != nil {
		return api.Response{}, err
	}

	return api.OK(converter.ToWorkspaceFileContent(content)), nil
}
