package api

import (
	"context"
	"encoding/json"
	"net/http"

	"github.com/muyue/muyue/internal/agent"
)

type ToolCallRequest struct {
	Tool string          `json:"tool"`
	Args json.RawMessage `json:"args"`
}

type ToolResult struct {
	Success  bool              `json:"success"`
	Tool     string            `json:"tool"`
	Result   *toolResponseData `json:"result,omitempty"`
	Error    string            `json:"error,omitempty"`
}

type toolResponseData struct {
	Content string            `json:"content"`
	IsError bool              `json:"is_error"`
	Meta    map[string]string `json:"meta,omitempty"`
}

func (s *Server) handleToolCall(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		writeError(w, "POST only", http.StatusMethodNotAllowed)
		return
	}

	var req ToolCallRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeError(w, err.Error(), http.StatusBadRequest)
		return
	}

	if req.Tool == "" {
		writeError(w, "tool is required", http.StatusBadRequest)
		return
	}

	ctx := context.Background()
	call := agent.ToolCall{
		ID:        generateMsgID(),
		Name:      req.Tool,
		Arguments: req.Args,
	}

	result, execErr := s.agentRegistry.Execute(ctx, call)
	if execErr != nil {
		writeJSON(w, ToolResult{
			Success: false,
			Tool:    req.Tool,
			Error:   execErr.Error(),
		})
		return
	}

	writeJSON(w, ToolResult{
		Success: true,
		Tool:    req.Tool,
		Result: &toolResponseData{
			Content: result.Content,
			IsError: result.IsError,
			Meta:    result.Meta,
		},
	})
}

func (s *Server) handleToolList(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		writeError(w, "GET only", http.StatusMethodNotAllowed)
		return
	}

	tools := s.agentRegistry.All()
	writeJSON(w, map[string]interface{}{
		"tools": tools,
		"count": len(tools),
	})
}