package com.rj.audio;

import com.alibaba.dashscope.audio.asr.transcription.*;
import com.alibaba.dashscope.common.TaskStatus;
import com.google.gson.*;

import java.util.Arrays;
import java.util.List;

/**
 * Author: Li Zhonghua  wx: spllzh  email(qq): 28668817@qq.com
 * Date: 2025/8/22 18:43
 *
 * https://help.aliyun.com/zh/model-studio/paraformer-recorded-speech-recognition-java-sdk
 *
 *
 **/
public class AudioAsynCallTest {

    public static void main(String[] args) {
        // 检查API Key
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        if (apiKey == null || apiKey.trim().isEmpty()) {
            System.err.println("错误: 请设置环境变量 DASHSCOPE_API_KEY");
            System.err.println("请按照以下步骤操作:");
            System.err.println("1. 登录阿里云控制台");
            System.err.println("2. 进入通义千问服务");
            System.err.println("3. 获取API Key");
            System.err.println("4. 设置环境变量: export DASHSCOPE_API_KEY=your-api-key");
            System.exit(1);
        }
        System.out.println(apiKey); //sk-0e5049c56b0f4ad3b65119c309a7eddc
        // 创建转写请求参数
        TranscriptionParam param =
                TranscriptionParam.builder()
                        .apiKey(apiKey)
                        .model("paraformer-v2")
                        // "language_hints"只支持paraformer-v2模型
                        .parameter("language_hints", new String[]{"zh", "en"})
                        .fileUrls(
                                Arrays.asList(
                                        "https://api.huayang-star.com/api/audio/1957424645898579969_a2db5d76-b52c-4289-9c7e-ed55d7f15e42.mp3",
                                        "https://api.huayang-star.com/api/audio/1957424665985101825_7b9b03f4-a458-4eb6-ac7b-b5cf827a2315.mp3",
                                        "https://api.huayang-star.com/api/audio/1957424645898579969_a2db5d76-b52c-4289-9c7e-ed55d7f15e42.mp3"))
                        .build();
        
        try {
            Transcription transcription = new Transcription();
            
            System.out.println("开始提交转写请求...");
            // 提交转写请求
            TranscriptionResult result = transcription.asyncCall(param);
            System.out.println("RequestId: " + result.getRequestId());
            System.out.println("TaskId: " + result.getTaskId());
            
            // Loop to get task execution results until task ends
            System.out.println("开始轮询任务状态...");
            int maxRetries = 60; // 最多等待60秒
            int retryCount = 0;
            
            while (retryCount < maxRetries) {
                result = transcription.fetch(TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
                System.out.println("任务状态: " + result.getTaskStatus() + " (重试次数: " + (retryCount + 1) + ")");
                
                if (result.getTaskStatus() == TaskStatus.SUCCEEDED) {
                    System.out.println("任务成功完成!");
                    List<TranscriptionTaskResult> taskResultList = result.getResults();


                    break;
                } else if (result.getTaskStatus() == TaskStatus.FAILED) {
                    System.err.println("任务失败");
                    System.exit(1);
                }
                
                Thread.sleep(1000);
                retryCount++;
            }
            
            if (retryCount >= maxRetries) {
                System.err.println("任务超时，请检查网络连接或稍后重试");
                System.exit(1);
            }
            
            // 打印结果
            System.out.println("转写结果:");
            System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(result.getOutput()));
            
        } catch (Exception e) {
            System.err.println("发生错误: " + e.getMessage());
            e.printStackTrace();
            
            // 提供具体的错误解决建议
            if (e.getMessage().contains("AccessDenied")) {
                System.err.println("\n可能的解决方案:");
                System.err.println("1. 检查API Key是否正确");
                System.err.println("2. 确认API Key有足够的权限");
                System.err.println("3. 检查音频文件URL是否可访问");
                System.err.println("4. 确认阿里云账户余额充足");
            }
        }
        
        System.exit(0);
    }
}
