package api

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

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

func (s *Server) handleImageGenerate(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		Prompt string `json:"prompt"`
		Size   string `json:"size"`
		Style  string `json:"style"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		jsonError(w, "invalid request: "+err.Error())
		return
	}

	if req.Prompt == "" {
		jsonError(w, "prompt is required")
		return
	}

	imgTool, err := agent.NewImageGenerationTool(s.config)
	if err != nil {
		jsonError(w, "image tool init: "+err.Error())
		return
	}

	args := map[string]interface{}{
		"prompt": req.Prompt,
		"size":   req.Size,
		"style":  req.Style,
	}

	result, err := imgTool.Execute(args)
	if err != nil {
		jsonError(w, fmt.Sprintf("generation failed: %v", err))
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write([]byte(result))
}
