package com.cmvr.web.controller.tts;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.annotation.Log;
import com.cmvr.common.core.controller.BaseController;
import com.cmvr.common.core.domain.AjaxResult;
import com.cmvr.common.core.page.TableDataInfo;
import com.cmvr.common.enums.BusinessType;
import com.cmvr.llm.service.LLMAiAgentPlatformService;
import com.cmvr.tts.domain.TtsSynthesizeTask;
import com.cmvr.tts.domain.vo.LlmQueryVo;
import com.cmvr.tts.service.ITtsSynthesizeTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * TTS合成任务Controller
 *
 * @author cmvr
 */
@RestController
@RequestMapping("/tts/task")
@Api(tags = "智能座舱-TTS合成任务管理")
@RequiredArgsConstructor
public class TtsSynthesizeTaskController extends BaseController {

    @Autowired
    private ITtsSynthesizeTaskService ttsTaskService;

    private final LLMAiAgentPlatformService llmAiAgentPlatformService;

    /**
     * 查询TTS合成任务列表
     */
    @ApiOperation("查询TTS合成任务列表")
    @PreAuthorize("@ss.hasPermi('tts:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(TtsSynthesizeTask task) {
        startPage();
        return ttsTaskService.selectTtsTaskList(task);
    }

    /**
     * 获取TTS合成任务详细信息
     */
    @ApiOperation("获取TTS合成任务详细信息")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(ttsTaskService.selectTtsTaskById(id));
    }

    /**
     * 新增TTS合成任务
     */
    @ApiOperation("新增TTS合成任务")
    @PreAuthorize("@ss.hasPermi('tts:task:add')")
    @Log(title = "TTS合成任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TtsSynthesizeTask task) {
        return success(ttsTaskService.insertTtsTask(task));
    }

    /**
     * 批量新增TTS合成任务
     */
    @ApiOperation("批量新增TTS合成任务")
    @PreAuthorize("@ss.hasPermi('tts:task:add')")
    @Log(title = "TTS合成任务", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult batchAdd(@RequestBody List<TtsSynthesizeTask> tasks) {
        return toAjax(ttsTaskService.batchInsertTtsTask(tasks));
    }

    /**
     * 修改TTS合成任务
     */
    @ApiOperation("修改TTS合成任务")
    @PreAuthorize("@ss.hasPermi('tts:task:edit')")
    @Log(title = "TTS合成任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TtsSynthesizeTask task) {
        return toAjax(ttsTaskService.updateTtsTask(task));
    }

    /**
     * 删除TTS合成任务
     */
    @ApiOperation("删除TTS合成任务")
    @PreAuthorize("@ss.hasPermi('tts:task:remove')")
    @Log(title = "TTS合成任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(ttsTaskService.deleteTtsTaskByIds(ids));
    }

    /**
     * 重生成TTS任务
     */
    @ApiOperation("重生成TTS任务")
    @PreAuthorize("@ss.hasPermi('tts:task:edit')")
    @Log(title = "TTS合成任务", businessType = BusinessType.UPDATE)
    @PostMapping("/regenerate/{id}")
    public AjaxResult regenerate(@PathVariable String id) {
        return toAjax(ttsTaskService.regenerateTask(id));
    }

    /**
     * 获取音频文件流
     */
    @ApiOperation("获取音频文件流")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping("/audio/{id}")
    public void getAudio(@PathVariable String id, HttpServletResponse response) {
        ttsTaskService.getAudioStream(id, response);
    }

    /**
     * 查询看板统计数据
     */
    @ApiOperation("查询看板统计数据")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping("/dashboard/stats")
    public AjaxResult getDashboardStats() {
        return success(ttsTaskService.getDashboardStats());
    }

    /**
     * 按语种统计
     */
    @ApiOperation("按语种统计")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping("/stats/language")
    public AjaxResult getStatsByLanguage() {
        return success(ttsTaskService.getStatsByLanguage());
    }

    /**
     * 按音色统计
     */
    @ApiOperation("按音色统计")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping("/stats/voice")
    public AjaxResult getStatsByVoice() {
        return success(ttsTaskService.getStatsByVoice());
    }

    /**
     * 按情绪统计
     */
    @ApiOperation("按情绪统计")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping("/stats/emotion")
    public AjaxResult getStatsByEmotion() {
        return success(ttsTaskService.getStatsByEmotion());
    }

    /**
     * 近7日趋势
     */
    @ApiOperation("近7日趋势")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @GetMapping("/stats/trend")
    public AjaxResult getLast7DaysTrend() {
        return success(ttsTaskService.getLast7DaysTrend());
    }

    /**
     * 文本泛化
     */
    @ApiOperation("文本泛化")
    @PreAuthorize("@ss.hasPermi('tts:task:query')")
    @PostMapping("/llm/query")
    public AjaxResult llmQuery(@RequestBody LlmQueryVo request) {
        // 闲聊key d9672ql4shh4136opsfg
        // 泛化key  d966pq54shh4nveh8d20
        JSONObject result = llmAiAgentPlatformService.query(
           null,
            request.getLanguage() + "," + request.getCount() + "," + request.getText(),
            "d96ammd4shh4nvehb6mg",
            false,
            null
        );
        
        // 解析LLM返回的结果，提取JSON数组
        String resultStr = result.getString("result");
        if (resultStr != null && !resultStr.isEmpty()) {
            // 尝试多种格式解析
            JSONArray jsonArray = parseJsonArray(resultStr);
            return success(jsonArray);
        }
        return success(new JSONArray());
    }

    /**
     * 解析JSON数组，兼容多种格式
     */
    private JSONArray parseJsonArray(String text) {
        if (text == null || text.isEmpty()) {
            return new JSONArray();
        }
        
        // 1. 直接尝试解析为JSON数组
        try {
            return JSONArray.parseArray(text);
        } catch (Exception e) {
            // 继续尝试其他格式
        }

        
        // 2. 移除markdown代码块标记
        String cleaned = text.replace("```json", "").replace("```", "").trim();
        try {
            return JSONArray.parseArray(cleaned);
        } catch (Exception e) {
            // 继续尝试其他格式
        }
        
        // 3. 尝试从文本中提取JSON数组（匹配 [...] 格式）
        int startIdx = text.indexOf("[");
        int endIdx = text.lastIndexOf("]");
        if (startIdx != -1 && endIdx != -1 && endIdx > startIdx) {
            String jsonStr = text.substring(startIdx, endIdx + 1);
            try {
                return JSONArray.parseArray(jsonStr);
            } catch (Exception e) {
                // 继续尝试其他格式
            }
        }
        
        // 4. 如果都失败，返回包含原始文本的数组
        return new JSONArray().fluentAdd(text);
    }

    /**
     * 保存任务到语料库
     */
    @ApiOperation("保存任务到语料库")
    @PreAuthorize("@ss.hasPermi('tts:task:edit')")
    @Log(title = "TTS合成任务", businessType = BusinessType.INSERT)
    @PostMapping("/Nsave-to-corpus/{taskId}/{categoryId}")
    public AjaxResult saveToCorpus(@PathVariable String taskId, @PathVariable String categoryId) {
        return toAjax(ttsTaskService.saveToCorpus(taskId, categoryId));
    }
}
