package com.xy.xyaicpzs.controller;

import com.xy.xyaicpzs.common.response.ApiResponse;
import com.xy.xyaicpzs.common.ResultUtils;
import com.xy.xyaicpzs.util.SpeechRecognizerDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 语音识别控制器
 */
@RestController
@RequestMapping("/api/speech")
public class SpeechRecognitionController {

    @Autowired
    private SpeechRecognizerDemo speechRecognizer;

    /**
     * 识别本地语音文件
     * @param filePath 文件路径
     * @param sampleRate 采样率
     * @return 识别结果
     */
    @GetMapping("/recognize")
    public ApiResponse<Map<String, String>> recognizeSpeech(
            @RequestParam("filePath") String filePath,
            @RequestParam(value = "sampleRate", defaultValue = "16000") int sampleRate) {
        
        String text = speechRecognizer.speechToText(filePath, sampleRate);
        Map<String, String> result = new HashMap<>();
        result.put("text", text);
        return ResultUtils.success(result);
    }

    /**
     * 上传并识别语音文件
     * @param file 上传的语音文件
     * @param sampleRate 采样率
     * @return 识别结果
     */
    @PostMapping("/upload-and-recognize")
    public ApiResponse<Map<String, String>> uploadAndRecognize(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "sampleRate", defaultValue = "16000") int sampleRate) {
        
        if (file.isEmpty()) {
            return ResultUtils.error(40001, "上传文件不能为空");
        }

        try {
            // 创建临时目录
            String tempDir = System.getProperty("java.io.tmpdir");
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(tempDir, fileName);
            
            // 保存上传的文件
            file.transferTo(filePath.toFile());
            
            // 识别语音
            String text = speechRecognizer.speechToText(filePath.toString(), sampleRate);
            
            // 删除临时文件
            Files.deleteIfExists(filePath);
            
            Map<String, String> result = new HashMap<>();
            result.put("text", text);
            return ResultUtils.success(result);
        } catch (IOException e) {
            return ResultUtils.error(50000, "文件处理失败：" + e.getMessage());
        }
    }
} 