package handlers

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"sproutclaw-web/internal/config"
	"sproutclaw-web/internal/models"
	"sproutclaw-web/internal/rpc"
)

// RegisterModels registers model-related routes.
func RegisterModels(r *gin.RouterGroup, cfg *config.Config, piClient *rpc.Client) {
	r.GET("/models", handleGetModels(piClient))
	r.POST("/model", handleSetModel(piClient))
	r.POST("/thinking", handleSetThinking(piClient))
}

func handleGetModels(piClient *rpc.Client) gin.HandlerFunc {
	return func(c *gin.Context) {
		resp, err := piClient.SendCmd(models.RPCCommand{Type: "get_available_models"})
		if err != nil {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
			return
		}
		if !resp.Success {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: resp.Error})
			return
		}
		c.JSON(http.StatusOK, jsonRaw(resp.Data))
	}
}

func handleSetModel(piClient *rpc.Client) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req models.SetModelRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, models.ErrorResponse{Error: err.Error()})
			return
		}
		resp, err := piClient.SendCmd(models.RPCCommand{
			Type:     "set_model",
			Provider: req.Provider,
			ModelID:  req.ModelID,
		})
		if err != nil {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
			return
		}
		if !resp.Success {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: resp.Error})
			return
		}
		c.JSON(http.StatusOK, gin.H{"model": jsonRaw(resp.Data)})
	}
}

func handleSetThinking(piClient *rpc.Client) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req models.SetThinkingRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, models.ErrorResponse{Error: err.Error()})
			return
		}
		resp, err := piClient.SendCmd(models.RPCCommand{
			Type:  "set_thinking_level",
			Level: req.Level,
		})
		if err != nil {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: err.Error()})
			return
		}
		if !resp.Success {
			c.JSON(http.StatusInternalServerError, models.ErrorResponse{Error: resp.Error})
			return
		}
		c.JSON(http.StatusOK, models.OKResponse{OK: true})
	}
}
