package webagent

import (
	"net/http"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/api"
	"github.com/tidbcloud/AgentTeam/internal/api/dto"
	"github.com/tidbcloud/AgentTeam/internal/store/agent"
)

// Get handles GET /api/v1/workspaces/:workspaceId/agents/:agentId/behavior-settings.
// It returns server-owned agent behavior settings without querying daemon or
// Machine diagnostic state.
func (handler *AgentBehaviorSettingsHandler) Get(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")
	}
	if handler == nil || handler.store == nil {
		return api.Response{}, api.ErrNotFound
	}

	settings, err := handler.store.AgentBehaviorSettingsForUser(r.Context(), r.UserID(), r.WorkspaceID(), agentID)
	if err != nil {
		return api.Response{}, err
	}
	return api.OK(agentBehaviorSettingsResponse(settings)), nil
}

// Update handles PATCH /api/v1/workspaces/:workspaceId/agents/:agentId/behavior-settings.
// "Agent reply enhancement" (VisibleReplyContract) is always-on, so this handler
// accepts the legacy visibleReplyContractEnabled field in any shape/value
// (true/false/null) for backward compatibility but no-ops: it never persists or
// applies a false value, and the response always reflects enabled=true.
func (handler *AgentBehaviorSettingsHandler) Update(r api.WorkspaceScopedJSON[dto.AgentBehaviorSettingsUpdateRequest]) (api.Response, error) {
	agentID := strings.TrimSpace(r.Gin.Param("agentId"))
	if agentID == "" {
		return api.Response{}, api.NewHTTPError(http.StatusBadRequest, "agentId is required")
	}
	if handler == nil || handler.store == nil {
		return api.Response{}, api.ErrNotFound
	}

	settings, err := handler.store.AgentBehaviorSettingsForUser(r.Context(), r.UserID(), r.WorkspaceID(), agentID)
	if err != nil {
		return api.Response{}, err
	}
	return api.OK(agentBehaviorSettingsResponse(settings)), nil
}

func agentBehaviorSettingsResponse(settings agent.BehaviorSettings) dto.AgentBehaviorSettingsResponse {
	// "Agent reply enhancement" (VisibleReplyContract) is always-on: the
	// effective value is hard-pinned to true here so no off-state ever leaks to
	// a client, regardless of any stale per-agent DB value.
	return dto.AgentBehaviorSettingsResponse{
		WorkspaceID:                          settings.WorkspaceID,
		AgentID:                              settings.AgentID,
		AccountVisibleReplyContractEnabled:   true,
		VisibleReplyContractEnabled:          true,
		EffectiveVisibleReplyContractEnabled: true,
	}
}
