package action

import (
	"bytes"
	"context"
	"fmt"
	"log/slog"
	"strconv"
	"text/template"

	"github.com/tidbcloud/jiraport/pkg/entity"
	"github.com/tidbcloud/jiraport/pkg/matcher"
)

type EvalCommand struct {
	logger *slog.Logger
}

func NewEvalCommand(logger *slog.Logger) (*EvalCommand, error) {
	return &EvalCommand{logger: logger}, nil
}

func (cmd *EvalCommand) Exec(ctx context.Context, actionExecInfo *entity.NotificationActionExecInfo, args ...string) (bool, string, error) {
	if len(args) == 0 {
		return true, "", nil
	}
	script := args[0]
	passedArgs := args[1:]

	compile := func(e string) (*template.Template, error) {
		tmpl := template.New("").Option("missingkey=zero").Funcs(matcher.CommonFuncs)
		tmpl, err := tmpl.Parse(e)
		if err != nil {
			return nil, fmt.Errorf("parse error in %#v, %w", e, err)
		}
		return tmpl, nil
	}

	executer, err := compile(script)
	if err != nil {
		return false, "", err
	}

	data := map[string]interface{}{
		"Args":  passedArgs,
		"Issue": actionExecInfo.Notification.Issue,
	}

	var buf bytes.Buffer
	err = executer.Execute(&buf, data)
	if err != nil {
		return false, "", err
	}
	output := buf.String()

	cmd.logger.Debug("eval script successfully",
		"issue", actionExecInfo.Notification.IssueKey,
		"script", script,
		"args", passedArgs,
		"output", output)

	regularized, err := strconv.ParseBool(output)
	if err != nil {
		return false, "", err
	}
	return regularized, "", nil
}
