package workflow

import (
	"agent/src/common"
	"agent/src/message"
	"agent/src/prompt"
	"encoding/json"
	"time"
)

type answerKeySymbols struct {
	KeySymbols []string `json:"key_symbols"`
}

func (task *Task) unittest_recommend() error {
	req := task.request.(*message.RequestExecUnitTestRecommend)
	msg, err := prompt.MakeExecUnitTestMore(req)
	if err != nil {
		task.client.WriteJson(&message.ResponseExecFail{
			RequestId: req.RequestId,
			Error: err.Error(),
		}, false)
	}

	answer, err := task.pool.llmGroup.Chat(task.ctx, msg)
	if err != nil {
		return err
	}
	_ = answer
	
	return nil
}

// TODO 与ideservice交互
func (task *Task) unittest_unsolved() error {
	req := task.request.(*message.RequestExecUnitTestRecommend)
	msg, err := prompt.MakeExecUnitTestMore(req)
	if err != nil {
		task.client.WriteJson(&message.ResponseExecFail{
			RequestId: req.RequestId,
			Error: err.Error(),
		}, false)
	}

	answer, err := task.pool.llmGroup.Chat(task.ctx, msg)
	if err != nil {
		return err
	}
	
	// {'key_symbols': ['direction', 'SNAKE', 'FOOD', 'score', 'label', 'food', 'snake', 'canvas', 'window', 'SPEED']}
	var keysymbols answerKeySymbols
	err = json.Unmarshal([]byte(answer), &keysymbols)
	if err == nil {
		want := make(chan []byte, 1)
		wantRequestId := common.NewRequestId()
		task.client.WantResponse(wantRequestId, want)
		timer := time.NewTimer(15*time.Second)
		select {
			case <-task.ctx.Done():
				return nil
			case <-timer.C:
				task.client.WriteJson(&message.ResponseExecFail{
					RequestId: req.RequestId,
					Error: "ideservice timeout",
				}, false)
			case res := <-want:
				_ = res
				// ...
		}

	}
	return nil
}