package handlers

import (
	"context"
	"fmt"
	"oral-friend/internal/initialization"
	"oral-friend/pkg/utils/audio"
	"os"

	larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
)

type AudioAction struct { /*è¯­éŸ³*/
}

func (*AudioAction) Execute(a *ActionInfo) bool {
	check := AzureModeCheck(a)
	if !check {
		return true
	}

	// å�ªæœ‰ç§�è�Šæ‰�è§£æ��è¯­éŸ³,å…¶ä»–ä¸�è§£æ��
	if a.info.handlerType != UserHandler {
		return true
	}

	//åˆ¤æ–­æ˜¯å�¦æ˜¯è¯­éŸ³
	if a.info.msgType == "audio" {
		fileKey := a.info.fileKey
		//fmt.Printf("fileKey: %s \n", fileKey)
		msgId := a.info.msgId
		//fmt.Println("msgId: ", *msgId)
		req := larkim.NewGetMessageResourceReqBuilder().MessageId(
			*msgId).FileKey(fileKey).Type("file").Build()
		resp, err := initialization.GetLarkClient().Im.MessageResource.Get(context.Background(), req)
		//fmt.Println(resp, err)
		if err != nil {
			fmt.Println(err)
			return true
		}
		f := fmt.Sprintf("%s.ogg", fileKey)
		resp.WriteFile(f)
		defer os.Remove(f)

		//fmt.Println("f: ", f)
		output := fmt.Sprintf("%s.mp3", fileKey)
		// ç­‰å¾…è½¬æ�¢å®Œæˆ�
		audio.OggToWavByPath(f, output)
		defer os.Remove(output)
		//fmt.Println("output: ", output)

		text, err := a.handler.gpt.AudioToText(output)
		if err != nil {
			fmt.Println(err)

			sendMsg(*a.ctx, fmt.Sprintf("ğŸ¤–ï¸�ï¼šè¯­éŸ³è½¬æ�¢å¤±è´¥ï¼Œè¯·ç¨�å��å†�è¯•ï½�\né”™è¯¯ä¿¡æ�¯: %v", err), a.info.msgId)
			return false
		}

		replyMsg(*a.ctx, fmt.Sprintf("ğŸ¤–ï¸�ï¼š%s", text), a.info.msgId)
		//fmt.Println("text: ", text)
		a.info.qParsed = text
		return true
	}

	return true

}
