package public

import (
	"ai_scheduler/internal/config"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg"
	"ai_scheduler/internal/pkg/utils_ollama"
	"context"
	"encoding/json"
	"fmt"

	"github.com/ollama/ollama/api"
)

// NormalChatTool 普通对话
type NormalChatTool struct {
	llm    *utils_ollama.Client
	config *config.Config
}

// NewNormalChatTool 实例普通对话
func NewNormalChatTool(llm *utils_ollama.Client, config *config.Config) *NormalChatTool {
	return &NormalChatTool{llm: llm, config: config}
}

// Name 返回工具名称
func (w *NormalChatTool) Name() string {
	return "normalChat"
}

// Description 返回工具描述
func (w *NormalChatTool) Description() string {
	return "用户想进行一般性问答"
}

type NormalChat struct {
	ChatContent string `json:"chat_content"`
}

// Definition 返回工具定义
func (w *NormalChatTool) Definition(ctx context.Context) entitys.ToolDefinition {
	return entitys.ToolDefinition{}
}

// Execute 执行直连天下订单详情查询
func (w *NormalChatTool) Execute(ctx context.Context, rec *entitys.Recognize) error {
	var req NormalChat
	if err := json.Unmarshal([]byte(rec.Match.Parameters), &req); err != nil {
		return fmt.Errorf("invalid zltxOrderDetail request: %w", err)
	}
	if req.ChatContent == "" {
		req.ChatContent = "介绍一下你能做什么"
	}

	// 这里可以集成真实的直连天下订单详情API
	return w.chat(rec, &req)
}

// getMockZltxOrderDetail 获取模拟直连天下订单详情数据
func (w *NormalChatTool) chat(rec *entitys.Recognize, chat *NormalChat) (err error) {
	//requireData.Ch <- entitys.Response{
	//	Index:   w.Name(),
	//	Content: "<think></think>",
	//	Type:    entitys.ResponseStream,
	//}

	err = w.llm.ChatStream(context.TODO(), rec.Ch, []api.Message{
		{
			Role:    "system",
			Content: "你是一个聊天助手",
		},
		{
			Role:    "assistant",
			Content: fmt.Sprintf("聊天记录：%s", pkg.JsonStringIgonErr(rec.ChatHis)),
		},
		{
			Role:    "user",
			Content: chat.ChatContent,
		},
	}, w.Name(), w.config.Ollama.GenerateModel)
	if err != nil {
		return fmt.Errorf("：%s", err)
	}

	return
}
