package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"io"
	"net/http"
	"os"
	"silk2audio/silk"
	"strings"
	"sync"

	"audio_transcoder/internal/svc"
	"audio_transcoder/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TranscoderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTranscoderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *TranscoderLogic {
	return &TranscoderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TranscoderLogic) Transcoder(req *types.Request) (resp *types.Response, err error) {
	if req.Path == "" {
		err = errors.New("path is empty")
		return
	}
	// 发起HTTP GET请求
	resp1, err := http.Get(req.Path)
	if err != nil {
		logx.Errorf("下载文件失败 error:", err.Error())
		return
	}
	defer resp1.Body.Close()
	if resp1.StatusCode != http.StatusOK {
		err = errors.New("download file failed")
		logx.Errorf("下载文件失败 error:", resp1.StatusCode)
		return
	}
	// 读取响应体内容
	silkPath := uuid.NewString() + ".silk" // 本地保存的文件路径
	silkFile, err := os.Create(silkPath)
	if err != nil {
		logx.Errorf("读取silk文件失败 error:", err.Error())
		return
	}
	defer func() {
		silkFile.Close()
		silk.FileRemove(silkPath)
	}()
	_, err = io.Copy(silkFile, resp1.Body)
	if err != nil {
		logx.Errorf("读取文件失败 error:", err.Error())
		return
	}
	// 转码
	wavPath, pcmPath := silk.TransSilkToWav(silkPath)
	wavFile, err := os.Open(wavPath)
	if err != nil {
		logx.Errorf("读取wav文件失败 error:", err.Error())
		return
	}
	defer func() {
		wavFile.Close()
		silk.FileRemove(wavPath)
	}()
	pcmFile, err := os.Open(pcmPath)
	if err != nil {
		logx.Errorf("读取pcm文件失败 error:", err.Error())
		return
	}
	defer func() {
		pcmFile.Close()
		silk.FileRemove(pcmPath)
	}()
	//多线程处理上传录音和语音识别
	var wg sync.WaitGroup
	wg.Add(2)
	//构建返回数据
	resp = &types.Response{}
	var err1, err2 error
	//上传录音
	go func() {
		defer wg.Done()
		bts, _ := io.ReadAll(wavFile)
		url, err := l.svcCtx.QiNiuSdk.Upload(bts, int64(len(bts)), wavPath)
		if err != nil {
			logx.Errorf("上传七牛云失败 error:", err.Error())
			return
		}
		err1 = err
		resp.Path = url
	}()
	//识别录音
	go func() {
		defer wg.Done()
		bts, _ := io.ReadAll(pcmFile)
		asrResp, err := l.svcCtx.AsrSdk.Asr(bts, "pcm", 16000)
		if err != nil {
			logx.Errorf("语音识别失败 error:", err.Error())
			return
		}
		err2 = err
		resp.Message = strings.Join(asrResp.Result, "\n")
	}()
	wg.Wait()
	//返回数据
	if err1 != nil {
		return nil, err1
	}
	if err2 != nil {
		return nil, err2
	}
	return
}
