package com.sonic.cow.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sonic.cow.domain.output.AsrOutput;
import com.sonic.cow.enums.DeductionTypeEnum;
import com.sonic.cow.enums.ToastResultCode;
import com.sonic.cow.event.outer.payload.UserDeductionStatPayload;
import com.sonic.cow.service.CommonSendMqService;
import com.sonic.cow.service.VoiceV2Service;
import com.sonic.cow.utils.KeyGenerator;
import com.sonic.lion.lib.client.PayClient;
import com.sonic.lion.lib.enums.BizType;
import com.sonic.lion.lib.input.BalanceCheckoutInput;
import com.sonic.lion.lib.output.AccountBuffOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.HashMap;

import static com.sonic.cow.utils.Constant.VOICE_DEDUCTION_AMOUNT;

/**
 * @description: 语音通话实现类
 * @author: mzc
 * @date: 2025-07-30 11:24
 **/
@Slf4j
@Service
public class VoiceV2ServiceImpl implements VoiceV2Service {

    @Autowired
    private CommonSendMqService commonSendMqService;
    @Autowired
    private PayClient payClient;

    @Override
    public AsrOutput asr(Long userId, Long aiId, File file) throws UnirestException {
        //检测余额是否不足
        boolean balanceIsInsufficient = checkBalanceIsInsufficient(userId, VOICE_DEDUCTION_AMOUNT);
        if (balanceIsInsufficient) {
            //余额不足，发送MQ，余额不足处理
            commonSendMqService.userBalanceInsufficientCheckoutMq(userId);
            ToastResultCode.USER_BALANCE_INSUFFICIENT.check(true);
        }
        HttpResponse<String> response = Unirest.post("https://api.openai.com/v1/audio/transcriptions")
                .header("Authorization", "Bearer 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")
                .field("file", file)
                .field("model", "gpt-4o-mini-transcribe")
                .asString();
        String result = response.getBody();
        log.info("===> asr result:{}", result);

        HashMap<Object, Object> extraMap = Maps.newHashMap();
        extraMap.put("asr", true);
        //异步扣费处理
        userDeductionStatSendMq(userId, aiId, extraMap);

        JSONObject jsonObject = JSONObject.parseObject(result);
        AsrOutput asrOutput = new AsrOutput();
        asrOutput.setContent(jsonObject.getString("text"));
        return asrOutput;
    }


    /**
     * 发送用户语音使用统计MQ
     *
     * @param userId
     * @param aiId
     * @param extraMap
     */
    private void userDeductionStatSendMq(Long userId, Long aiId, HashMap<Object, Object> extraMap) {
        commonSendMqService.userDeductionStatSendMq(UserDeductionStatPayload.builder()
                .userId(userId)
                .aiId(aiId)
                .deductionType(DeductionTypeEnum.VOICE)
                .bizTime(LocalDateTime.now())
                .extra(JSON.toJSONString(extraMap))
                .build());
    }

    /**
     * 检测余额是否不足
     *
     * @param userId
     * @param amount 本次金额
     * @return
     */
    @Override
    public boolean checkBalanceIsInsufficient(Long userId, Long amount) {
        try {
            AccountBuffOutput accountBuff = payClient.getAccountBuff(userId);
            Long balance = accountBuff != null && accountBuff.getBalance() > 0 ? accountBuff.getBalance() : 0;
            log.info("checkBalanceIsInsufficient balance:{},totalDeductionAmount:{}", balance,  amount);
            if (balance < amount) {
                return true;
            }
        } catch (Exception e) {
            log.error("checkBalanceIsInsufficient error:", e);
        }
        return false;
    }

}