package com.rj.speech;

import com.google.gson.*;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 快速语音识别结果演示
 * 直接测试您提供的transcription_url
 * Author: Li Zhonghua  wx: spllzh  email(qq): 28668817@qq.com
 * Date: 2025/8/24
 */
public class DownloadParse {

    public static void main(String[] args) {
        System.out.println("🎤 快速语音识别结果演示");
        System.out.println("==================================");
        
        // 您提供的transcription_url
        String transcriptionUrl = "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/prod/paraformer-v2/20250824/10%3A42/83ab4e35-2db8-4eea-b890-7a6ed353f722-1.json?Expires=1756089779&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=KzkVdetZnpVu1WkLqt6PRMtjIxU%3D";
        
        try {
            System.out.println("📥 开始下载识别结果...");
            System.out.println("URL: " + transcriptionUrl);
            
            String jsonContent = downloadTranscriptionResult(transcriptionUrl);
            
            if (jsonContent != null) {
                System.out.println("✅ 下载成功，开始解析...");
                parseAndOutputTranscription(jsonContent);
            } else {
                System.err.println("❌ 下载失败");
            }
            
        } catch (Exception e) {
            System.err.println("💥 发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        
        System.out.println("\n🏁 演示完成");
    }
    
    /**
     * 下载识别结果文件
     */
    private static String downloadTranscriptionResult(String transcriptionUrl) {
        try {
            System.out.println("正在下载识别结果...");
            
            HttpURLConnection connection = (HttpURLConnection) new URL(transcriptionUrl).openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(30000);
            connection.connect();
            
            if (connection.getResponseCode() == 200) {
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8")
                );
                
                StringBuilder content = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
                reader.close();
                
                System.out.println("下载完成，文件大小: " + content.length() + " 字符");
                return content.toString();
            } else {
                System.err.println("下载失败，HTTP状态码: " + connection.getResponseCode());
                return null;
            }
            
        } catch (Exception e) {
            System.err.println("下载识别结果时发生错误: " + e.getMessage());
            return null;
        }
    }
    
    /**
     * 解析并输出识别内容
     */
    private static void parseAndOutputTranscription(String jsonContent) {
        try {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            JsonObject jsonObject = gson.fromJson(jsonContent, JsonObject.class);
            
            System.out.println("\n🎉 识别内容解析结果:");
            System.out.println("==================================");
            
            if (jsonObject.has("transcripts")) {
                JsonArray transcripts = jsonObject.getAsJsonArray("transcripts");
                
                for (JsonElement transcriptElement : transcripts) {
                    JsonObject transcript = transcriptElement.getAsJsonObject();
                    
                    if (transcript.has("sentences")) {
                        JsonArray sentences = transcript.getAsJsonArray("sentences");
                        
                        System.out.println("🗣️  识别到的文本内容:");
                        System.out.println("----------------------------------------");
                        
                        StringBuilder fullText = new StringBuilder();
                        
                        for (JsonElement sentenceElement : sentences) {
                            JsonObject sentence = sentenceElement.getAsJsonObject();
                            
                            String content = "";
                            String startTime = "";
                            String endTime = "";
                            String speakerId = "未知";
                            
                            if (sentence.has("text")) {
                                content = sentence.get("text").getAsString();
                                fullText.append(content).append(" ");
                            }
                            if (sentence.has("begin_time")) {
                                startTime = formatTime(sentence.get("begin_time").getAsDouble());
                            }
                            if (sentence.has("end_time")) {
                                endTime = formatTime(sentence.get("end_time").getAsDouble());
                            }
                            if (sentence.has("speaker_id")) {
                                speakerId = sentence.get("speaker_id").getAsString();
                            }
                            
                            // 输出带时间戳和说话人ID的句子
                            if (!"未知".equals(speakerId)) {
                                System.out.printf("👤 说话人%s [%s - %s]: %s\n", speakerId, startTime, endTime, content);
                            } else {
                                System.out.printf("💬 [%s - %s]: %s\n", startTime, endTime, content);
                            }
                        }
                        
                        System.out.println("----------------------------------------");
                        System.out.println("📝 完整识别文本:");
                        System.out.println(fullText.toString().trim());
                        System.out.println("----------------------------------------");
                        System.out.println("✅ 识别内容解析完成");
                    }
                }
            } else {
                System.out.println("⚠️  未找到识别文本内容");
                // 输出原始JSON以便调试
                System.out.println("原始JSON内容:");
                System.out.println(gson.toJson(jsonObject));
            }
            
        } catch (Exception e) {
            System.err.println("❌ 解析识别内容失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 格式化时间显示
     */
    private static String formatTime(double milliseconds) {
        int minutes = (int) (milliseconds / 60000);
        int secs = (int) ((milliseconds % 60000) / 1000);
        int millis = (int) (milliseconds % 1000);
        return String.format("%02d:%02d.%03d", minutes, secs, millis);
    }
}
