package com.example.demo.controller;

import com.example.demo.model.NovelComicTask;
import com.example.demo.repository.NovelComicTaskRepository;
import com.example.demo.service.CosService;
import com.example.demo.service.CozeWorkflowService;
import com.example.demo.util.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 小说漫剧生成 API 控制器
 * 使用异步模式：提交任务立即返回 taskId，前端轮询状态
 */
@RestController
@RequestMapping("/api/novel-comic")
public class NovelComicApiController {

    private static final Logger logger = LoggerFactory.getLogger(NovelComicApiController.class);

    private static final long MAX_MUSIC_FILE_SIZE = 50 * 1024 * 1024; // 50MB
    private static final Set<String> ALLOWED_MUSIC_TYPES = Set.of(
            "audio/mpeg", "audio/wav", "audio/aac", "audio/ogg",
            "audio/mp4", "audio/x-m4a", "audio/flac", "audio/webm"
    );

    @Autowired
    private CozeWorkflowService cozeWorkflowService;

    @Autowired
    private CosService cosService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private NovelComicTaskRepository novelComicTaskRepository;

    /**
     * 创建小说漫剧生成任务（异步模式）
     * 立即返回 taskId (executeId)，前端通过 /status 接口轮询结果
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createNovelComic(
            @RequestParam("storyBackground") String storyBackground,
            @RequestParam("storyScript") String storyScript,
            @RequestParam(value = "theme", required = false, defaultValue = "") String theme,
            @RequestParam(value = "backgroundMusic", required = false) MultipartFile backgroundMusic,
            @RequestHeader("Authorization") String token) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 必填校验
            if (storyBackground == null || storyBackground.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "故事背景不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (storyScript == null || storyScript.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "故事文案不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 验证音乐文件（如果有），上传到 COS 获取 URL
            String musicUrl = "";
            if (backgroundMusic != null && !backgroundMusic.isEmpty()) {
                if (backgroundMusic.getSize() > MAX_MUSIC_FILE_SIZE) {
                    response.put("success", false);
                    response.put("message", "音乐文件不能超过 50MB");
                    return ResponseEntity.badRequest().body(response);
                }

                String contentType = backgroundMusic.getContentType();
                if (contentType == null || !ALLOWED_MUSIC_TYPES.contains(contentType)) {
                    response.put("success", false);
                    response.put("message", "不支持的音频格式，请上传 MP3、WAV、AAC、OGG 等格式");
                    return ResponseEntity.badRequest().body(response);
                }

                String musicFileName = backgroundMusic.getOriginalFilename();
                logger.info("音乐文件: name={}, size={}, type={}", musicFileName,
                        backgroundMusic.getSize(), contentType);

                String cosFileName = "bgm_" + System.currentTimeMillis() + "_" + musicFileName;
                musicUrl = cosService.uploadBytes(
                        backgroundMusic.getBytes(), cosFileName, contentType);

                if (musicUrl == null || musicUrl.isEmpty()) {
                    response.put("success", false);
                    response.put("message", "音乐文件上传失败，请稍后重试");
                    return ResponseEntity.status(500).body(response);
                }
                logger.info("音乐文件已上传到 COS: {}", musicUrl);
            }

            logger.info("小说漫剧异步提交: user={}, theme={}, backgroundLen={}, scriptLen={}, hasMusicUrl={}",
                    username, theme, storyBackground.length(), storyScript.length(), !musicUrl.isEmpty());

            // 异步提交 Coze 工作流 — 立即返回 executeId
            Map<String, Object> result = cozeWorkflowService.generateNovelComicAsync(
                    theme, storyBackground.trim(), musicUrl, storyScript.trim());

            if (Boolean.TRUE.equals(result.get("success"))) {
                String executeId = (String) result.get("executeId");

                // 持久化任务记录
                try {
                    NovelComicTask task = new NovelComicTask(
                            executeId, username, theme,
                            storyBackground.trim(), storyScript.trim(), musicUrl);
                    novelComicTaskRepository.save(task);
                    logger.info("任务记录已保存: taskId={}", executeId);
                } catch (Exception dbEx) {
                    logger.warn("保存任务记录失败（不影响生成）: {}", dbEx.getMessage());
                }

                response.put("success", true);
                response.put("taskId", executeId);
                response.put("message", "任务已提交，正在后台生成中");
                logger.info("小说漫剧任务提交成功: user={}, taskId={}", username, executeId);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", result.getOrDefault("message", "任务提交失败"));
                logger.warn("小说漫剧任务提交失败: user={}, message={}", username, result.get("message"));
                return ResponseEntity.ok(response);
            }

        } catch (Exception e) {
            logger.error("小说漫剧生成异常", e);
            response.put("success", false);
            response.put("message", "服务器内部错误: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 查询任务执行状态（前端轮询）
     * 返回: status=RUNNING/SUCCESS/FAIL, data, message
     */
    @GetMapping("/status/{executeId}")
    public ResponseEntity<Map<String, Object>> getTaskStatus(
            @PathVariable String executeId,
            @RequestHeader("Authorization") String token) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 验证用户身份
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 查询 Coze 工作流执行状态
            Map<String, Object> statusResult = cozeWorkflowService.getNovelComicStatus(executeId);

            String status = (String) statusResult.getOrDefault("status", "RUNNING");
            response.put("success", true);
            response.put("status", status);

            if ("SUCCESS".equals(status)) {
                Object data = statusResult.get("data");
                response.put("data", data);
                // 更新数据库记录
                updateTaskRecord(executeId, status, data, null);
            } else if ("FAIL".equals(status)) {
                String msg = (String) statusResult.getOrDefault("message", "生成失败");
                response.put("message", msg);
                updateTaskRecord(executeId, status, null, msg);
            }

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("查询任务状态异常: executeId={}", executeId, e);
            response.put("success", false);
            response.put("status", "FAIL");
            response.put("message", "查询状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取用户历史记录（分页）
     */
    @GetMapping("/history")
    public ResponseEntity<Map<String, Object>> getHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestHeader("Authorization") String token) {

        Map<String, Object> response = new HashMap<>();
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            Page<NovelComicTask> tasks = novelComicTaskRepository
                    .findByUsernameOrderByCreatedAtDesc(username, PageRequest.of(page, size));

            // 转换为前端需要的格式
            List<Map<String, Object>> items = new ArrayList<>();
            for (NovelComicTask task : tasks.getContent()) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", task.getId());
                item.put("taskId", task.getTaskId());
                item.put("theme", task.getTheme());
                item.put("storyBackground", task.getStoryBackground());
                item.put("storyScript", task.getStoryScript());
                item.put("status", task.getStatus().name());
                item.put("result", task.getResult());
                item.put("errorMessage", task.getErrorMessage());
                item.put("createdAt", task.getCreatedAt());
                items.add(item);
            }

            Map<String, Object> data = new HashMap<>();
            data.put("content", items);
            data.put("totalElements", tasks.getTotalElements());
            data.put("totalPages", tasks.getTotalPages());

            response.put("success", true);
            response.put("data", data);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取历史记录失败", e);
            response.put("success", false);
            response.put("message", "获取历史记录失败");
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取 Coze 配置状态（调试用）
     */
    @GetMapping("/config-status")
    public ResponseEntity<Map<String, Object>> getConfigStatus() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", cozeWorkflowService.getConfigStatus());
        return ResponseEntity.ok(response);
    }

    /**
     * 删除历史记录
     * 不需要事务，不需要先查询，直接删除并通过影响行数判断
     */
    @DeleteMapping("/history/{id}")
    public ResponseEntity<Map<String, Object>> deleteHistory(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {

        Map<String, Object> response = new HashMap<>();

        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            int deleted = novelComicTaskRepository.deleteByIdAndUsername(id, username);
            
            if (deleted > 0) {
                logger.info("删除历史记录成功: id={}, user={}", id, username);
                response.put("success", true);
                response.put("message", "删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "记录不存在或无权限删除");
                return ResponseEntity.status(404).body(response);
            }

        } catch (Exception e) {
            logger.error("删除历史记录异常: id={}", id, e);
            response.put("success", false);
            response.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新数据库中的任务记录
     */
    private void updateTaskRecord(String executeId, String status, Object data, String errorMsg) {
        try {
            novelComicTaskRepository.findByTaskId(executeId).ifPresent(task -> {
                // 只更新终态，避免重复写入
                if (task.getStatus() == NovelComicTask.TaskStatus.COMPLETED
                        || task.getStatus() == NovelComicTask.TaskStatus.FAILED) {
                    return;
                }
                if ("SUCCESS".equals(status)) {
                    String resultStr = data instanceof String ? (String) data : String.valueOf(data);
                    task.markCompleted(resultStr);
                    novelComicTaskRepository.save(task);
                } else if ("FAIL".equals(status)) {
                    task.markFailed(errorMsg);
                    novelComicTaskRepository.save(task);
                }
            });
        } catch (Exception e) {
            logger.warn("更新任务记录失败: {}", e.getMessage());
        }
    }

    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            return null;
        } catch (Exception e) {
            logger.error("Token 解析失败", e);
            return null;
        }
    }
}
