package tools

import (
	"context"
	"encoding/json"
	"fmt"

	externalAgent "github.com/pardnchiu/agenvoy/internal/tools/agent/external"
	"github.com/pardnchiu/agenvoy/internal/tools/calculator"
	"github.com/pardnchiu/agenvoy/internal/tools/errorMemory"
	"github.com/pardnchiu/agenvoy/internal/tools/external"
	"github.com/pardnchiu/agenvoy/internal/tools/file"
	"github.com/pardnchiu/agenvoy/internal/tools/listLog"
	toolRegister "github.com/pardnchiu/agenvoy/internal/tools/register"
	toolScheduler "github.com/pardnchiu/agenvoy/internal/tools/scheduler"
	toolSearcher "github.com/pardnchiu/agenvoy/internal/tools/searcher"
	toolTypes "github.com/pardnchiu/agenvoy/internal/tools/types"

	"github.com/pardnchiu/agenvoy/internal/tools/fetchPage"
	_ "github.com/pardnchiu/agenvoy/internal/tools/git"
)

func init() {
	registSearchConversationHistory()

	external.Register()
	externalAgent.Register()
	fetchPage.Register()
	file.Register()
	errorMemory.Register()
	listLog.Register()
	toolScheduler.Register()
	toolSearcher.Register()

	registRunCommand()
	registAskUser()
	registStoreSecret()
	registUpdatePage()

	toolRegister.RegistGroup("api_", func(ctx context.Context, e *toolTypes.Executor, name string, args json.RawMessage) (string, error) {
		if e.APIToolbox == nil || !e.APIToolbox.IsExist(name) {
			return "", fmt.Errorf("not exist: %s", name)
		}

		var params map[string]any
		if err := json.Unmarshal(args, &params); err != nil {
			return "", fmt.Errorf("json.Unmarshal: %w", err)
		}
		return e.APIToolbox.Execute(ctx, name, params)
	})

	toolRegister.RegistGroup("script_", func(ctx context.Context, e *toolTypes.Executor, name string, args json.RawMessage) (string, error) {
		if e.ScriptToolbox == nil || !e.ScriptToolbox.IsExist(name) {
			return "", fmt.Errorf("not exist: %s", name)
		}
		return e.ScriptToolbox.Execute(ctx, name, args, e.WorkDir)
	})

	// * generated by agent, need to be checked and optimized by human
	calculator.Register()
}
