package org.dromara.talk.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.talk.service.ITtsService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

import java.util.concurrent.CompletableFuture;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/talk")
@CrossOrigin(origins = "*", maxAge = 3600)
public class ChatController {

    private final ITtsService ttsService;

    @SaIgnore
    @PostMapping("/message")
    public Map<String, Object> handleMessage(@RequestBody Map<String, Object> request) {
        String userMessage = (String) request.get("message");
        Long agentId = request.get("agentId") != null ?
            Long.valueOf(request.get("agentId").toString()) : null;

        log.info("收到用户消息: {}, 客服ID: {}", userMessage, agentId);

        // 生成客服回复（后期接入AI）
        String reply = generateReply(userMessage);

        // 异步合成语音
        CompletableFuture<String> audioFuture = new CompletableFuture<>();

        ttsService.synthesize(reply, new ITtsService.AudioCallback() {
            private final java.io.ByteArrayOutputStream audioBytes = new java.io.ByteArrayOutputStream();

            @Override
            public void onAudio(String base64Audio, int status) {
                log.info("收到音频数据: status={}, 数据长度={}", status, base64Audio != null ? base64Audio.length() : 0);
                try {
                    // 先解码base64为字节,然后写入流
                    byte[] decoded = java.util.Base64.getDecoder().decode(base64Audio);
                    audioBytes.write(decoded);
                    log.info("已写入字节数: {}", decoded.length);
                } catch (Exception e) {
                    log.error("解码音频数据失败", e);
                }
                if (status == 2) {
                    // 将完整的字节数组重新编码为base64
                    String finalBase64 = java.util.Base64.getEncoder().encodeToString(audioBytes.toByteArray());
                    log.info("音频合成完成,原始字节数={}, base64长度={}", audioBytes.size(), finalBase64.length());
                    audioFuture.complete(finalBase64);
                }
            }

            @Override
            public void onError(int code, String message) {
                log.error("TTS合成失败: {}", message);
                audioFuture.complete(null);
            }
        });

        // 等待音频合成完成（最多10秒）
        String audioBase64 = null;
        try {
            audioBase64 = audioFuture.get(10, java.util.concurrent.TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("等待音频合成超时", e);
        }

        // 返回响应
        Map<String, Object> response = new HashMap<>();
        response.put("reply", reply);
        response.put("audio", audioBase64);
        response.put("timestamp", System.currentTimeMillis());

        log.info("准备返回响应: reply长度={}, audio长度={}", reply != null ? reply.length() : 0, audioBase64 != null ? audioBase64.length() : 0);

        return response;
    }

    private String generateReply(String userMessage) {
        // 默认回复（后期接入AI）
        return "收到您的消息：" + userMessage;
    }
}
