/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.controller
 * @ClassName: SummaryController
 * @Description: 总结相关控制器
 * @Author: 张志锋
 * @Date: 2025-11-03
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.controller;

import com.zhpb.gdyd_zhpb_zgf.context.ModelRequestContextHolder;
import com.zhpb.gdyd_zhpb_zgf.dto.SummaryResponse;
import com.zhpb.gdyd_zhpb_zgf.entity.mysql.FileDirectory;
import com.zhpb.gdyd_zhpb_zgf.repository.mysql.FileDirectoryRepository;
import com.zhpb.gdyd_zhpb_zgf.service.AIModelService;
import com.zhpb.gdyd_zhpb_zgf.service.ChapterContentResolver;
import com.zhpb.gdyd_zhpb_zgf.service.FilePathResolver;
import com.zhpb.gdyd_zhpb_zgf.service.PromptTemplateService;
import com.zhpb.gdyd_zhpb_zgf.utils.HttpClientUtils;
import com.alibaba.fastjson2.JSON;
import org.springframework.http.ResponseEntity;

import java.util.*;
import java.util.stream.Collectors;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import com.zhpb.gdyd_zhpb_zgf.service.UserLogService;

import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.ArrayList;
import java.util.List;

/**
 * 总结相关控制器
 */
@RestController
@RequestMapping("/api/v1/summary")
@Tag(name = "总结管理", description = "文件目录和章节总结相关接口")
public class SummaryController {

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

    @Autowired
    private FileDirectoryRepository fileDirectoryRepository;

    @Autowired
    private com.zhpb.gdyd_zhpb_zgf.repository.mysql.FileRepository fileRepository;

    @Autowired
    private com.zhpb.gdyd_zhpb_zgf.service.FileService fileService;

    @Autowired
    private PromptTemplateService promptTemplateService;

    @Autowired
    private AIModelService aiModelService;

    @Autowired
    private ChapterContentResolver chapterContentResolver;

    @Autowired
    private org.springframework.core.env.Environment environment;

    @Autowired
    private FilePathResolver filePathResolver;
    
    @Autowired
    private UserLogService userLogService;

    @GetMapping("/directory/count")
    @Operation(summary = "查询t_file_directory表记录数")
    public ResponseEntity<?> getDirectoryCount() {
        logger.info("查询t_file_directory表记录数");
        try {
            long count = fileDirectoryRepository.count();
            logger.info("t_file_directory表总记录数: {}", count);

            Map<String, Object> response = new HashMap<>();
            response.put("table", "t_file_directory");
            response.put("totalRecords", count);
            response.put("timestamp", java.time.LocalDateTime.now());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("查询表记录数失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    @GetMapping("/directory/status")
    @Operation(summary = "检查文件目录状态", description = "检查文件是否存在以及是否有目录数据")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    public ResponseEntity<Map<String, Object>> getDirectoryStatus(
            @Parameter(description = "文件ID", required = true)
            @RequestParam String file_id) {

        logger.info("检查文件目录状态: fileId={}", file_id);

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

        try {
            // 检查文件是否在t_file表中存在
            java.util.Optional<com.zhpb.gdyd_zhpb_zgf.entity.mysql.File> fileOptional = fileRepository.findByFileId(file_id);
            boolean fileExists = fileOptional.isPresent();

            // 检查目录数据是否存在
            long directoryCount = fileDirectoryRepository.countByFileId(file_id);

            result.put("fileId", file_id);
            result.put("fileExists", fileExists);
            result.put("directoryExists", directoryCount > 0);
            result.put("directoryCount", directoryCount);

            if (fileExists) {
                com.zhpb.gdyd_zhpb_zgf.entity.mysql.File file = fileOptional.get();
                result.put("fileName", file.getFileName());
                result.put("fileSize", file.getFileSize());
                result.put("uploadTime", file.getCreateTime());
                result.put("vectorizationStatus", file.getVectorizationStatus());
            }

            result.put("code", 0);
            result.put("message", "查询成功");

        } catch (Exception e) {
            logger.error("检查文件目录状态失败", e);
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
        }

        return ResponseEntity.ok(result);
    }

    @GetMapping("/directory")
    @Operation(summary = "获取文件目录结构", description = "根据文件ID获取文件的目录结构")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "文件不存在"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<SummaryResponse.DirectoryResponse> getDirectory(
            @Parameter(description = "文件ID", required = true)
            @RequestParam String file_id) {

        logger.info("查询文件目录: fileId={}", file_id);

        try {
            List<FileDirectory> directories = fileDirectoryRepository.findByFileIdOrderBySortOrderAsc(file_id);

            if (directories.isEmpty()) {
                SummaryResponse.DirectoryResponse response = new SummaryResponse.DirectoryResponse();
                response.setCode(200);
                response.setMessage("文件目录不存在，可能文件还没有进行目录抽取处理");
                return ResponseEntity.ok().body(response);
            }

            // 构建树形结构
            List<SummaryResponse.DirectoryItem> directoryItems = buildDirectoryTree(directories);

            SummaryResponse.DirectoryData data = new SummaryResponse.DirectoryData();
            data.setFileId(file_id);
            data.setDirectory(directoryItems);

            SummaryResponse.DirectoryResponse response = new SummaryResponse.DirectoryResponse();
            response.setCode(0);
            response.setMessage("Success");
            response.setData(data);

            // 记录用户操作日志
            HttpServletRequest httpRequest = ((org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes())
                .getRequest();
            userLogService.logUserOperation(null, null, null, 
                "VIEW_CATALOG", "查看文件目录结构", file_id, httpRequest);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("查询文件目录失败", e);
            SummaryResponse.DirectoryResponse response = new SummaryResponse.DirectoryResponse();
            response.setCode(500);
            response.setMessage("系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @GetMapping("/chapter")
    @Operation(summary = "获取章节总结", description = "根据文件ID和章节ID获取章节总结")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "章节不存在"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<SummaryResponse.ChapterSummaryResponse> getChapterSummary(
            @Parameter(description = "文件ID", required = true)
            @RequestParam String file_id,
            @Parameter(description = "章节ID", required = true)
            @RequestParam String chapter_id) {

        logger.info("查询章节总结: fileId={}, chapterId={}", file_id, chapter_id);

        try {
            FileDirectory directory = fileDirectoryRepository.findByFileIdAndChapterId(file_id, chapter_id);

            if (directory == null) {
                SummaryResponse.ChapterSummaryResponse response = new SummaryResponse.ChapterSummaryResponse();
                response.setCode(200);
                response.setMessage("章节不存在");
                return ResponseEntity.ok().body(response);
            }

            // 如果数据库中有总结内容，直接返回
            if (directory.getSummary() != null && !directory.getSummary().isEmpty()) {
                SummaryResponse.ChapterSummaryData data = new SummaryResponse.ChapterSummaryData();
                data.setFileId(file_id);
                data.setChapterId(chapter_id);
                data.setSummary(directory.getSummary());

                // 构建sources信息（如果需要的话）
                data.setSources(new ArrayList<>());

                SummaryResponse.ChapterSummaryResponse response = new SummaryResponse.ChapterSummaryResponse();
                response.setCode(0);
                response.setMessage("Success");
                response.setData(data);

                // 记录用户操作日志
                HttpServletRequest httpRequest = ((org.springframework.web.context.request.ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes())
                    .getRequest();
                userLogService.logUserOperation(null, null, null, 
                    "CATALOG_SUMMARY", "查看章节总结", chapter_id, httpRequest);

                return ResponseEntity.ok(response);
            }

            // 如果数据库中没有总结内容，实时调用模型生成（3分钟超时）
            try {
                logger.info("数据库中无总结内容，实时调用模型生成: fileId={}, chapterId={}", file_id, chapter_id);

                // 使用CompletableFuture实现3分钟超时控制
                final FileDirectory finalDirectory = directory;
                java.util.concurrent.CompletableFuture<String> summaryFuture = java.util.concurrent.CompletableFuture.supplyAsync(() -> {
                    return generateChapterSummaryWithDeepSeek(finalDirectory);
                });

                // 等待最多3分钟
                String summaryContent = null;
                try {
                    summaryContent = summaryFuture.get(3, java.util.concurrent.TimeUnit.MINUTES);
                } catch (java.util.concurrent.TimeoutException te) {
                    logger.warn("实时生成摘要超时(3分钟): fileId={}, chapterId={}", file_id, chapter_id);
                    summaryFuture.cancel(true);
                }

                if (summaryContent != null && !summaryContent.isEmpty()) {
                    // 更新数据库
                    directory.setSummary(summaryContent);
                    fileDirectoryRepository.save(directory);
                    logger.info("实时生成摘要成功并保存: fileId={}, chapterId={}, 长度={}", 
                        file_id, chapter_id, summaryContent.length());

                    SummaryResponse.ChapterSummaryData data = new SummaryResponse.ChapterSummaryData();
                    data.setFileId(file_id);
                    data.setChapterId(chapter_id);
                    data.setSummary(summaryContent);
                    data.setSources(new ArrayList<>());

                    SummaryResponse.ChapterSummaryResponse response = new SummaryResponse.ChapterSummaryResponse();
                    response.setCode(0);
                    response.setMessage("Success");
                    response.setData(data);

                    return ResponseEntity.ok(response);
                }
            } catch (Exception e) {
                logger.warn("实时生成章节总结失败: fileId={}, chapterId={}, error={}", file_id, chapter_id, e.getMessage());
            }

            // 如果都获取不到，返回默认消息
            SummaryResponse.ChapterSummaryData data = new SummaryResponse.ChapterSummaryData();
            data.setFileId(file_id);
            data.setChapterId(chapter_id);
            data.setSummary("暂无总结内容");
            data.setSources(new ArrayList<>());

            SummaryResponse.ChapterSummaryResponse response = new SummaryResponse.ChapterSummaryResponse();
            response.setCode(0);
            response.setMessage("Success");
            response.setData(data);

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("查询章节总结失败", e);
            SummaryResponse.ChapterSummaryResponse response = new SummaryResponse.ChapterSummaryResponse();
            response.setCode(500);
            response.setMessage("系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 从外部API获取章节总结（这里使用DeepSeek API）
     */
    private String fetchChapterSummaryFromExternalAPI(String fileId, String chapterId) {
        try {
            // 获取章节信息
            com.zhpb.gdyd_zhpb_zgf.entity.mysql.FileDirectory directory = fileDirectoryRepository.findByFileIdAndChapterId(fileId, chapterId);
            if (directory == null) {
                logger.warn("未找到章节信息: fileId={}, chapterId={}", fileId, chapterId);
                return null;
            }

            // 使用DeepSeek API生成章节总结
            return generateChapterSummaryWithDeepSeek(directory);

        } catch (Exception e) {
            logger.error("获取章节总结失败", e);
            return null;
        }
    }

    /**
     * 使用AI模型生成章节总结
     */
    private String generateChapterSummaryWithDeepSeek(com.zhpb.gdyd_zhpb_zgf.entity.mysql.FileDirectory directory) {
        try {
            // 获取文档摘要提示词模板
            com.zhpb.gdyd_zhpb_zgf.entity.mysql.PromptTemplate summaryTemplate = promptTemplateService.getActiveTemplate("summary");
            if (summaryTemplate == null) {
                throw new RuntimeException("未找到激活的文档摘要提示词模板，请在提示词配置页面启用或创建summary类型的提示词模板");
            }

            String promptTemplate = summaryTemplate.getPromptContent();
            logger.info("使用数据库提示词模板: {} (ID: {}), 内容长度: {}", summaryTemplate.getTemplateName(), summaryTemplate.getTemplateId(), promptTemplate.length());
            logger.debug("提示词内容: {}", promptTemplate);

            // 使用模板替换变量
            String prompt = promptTemplate.replace("{title}", directory.getTitle());
            logger.debug("最终使用的提示词: {}", prompt);

            logger.info("调用AI模型生成章节总结: chapterId={}", directory.getChapterId());

            String userMessage = chapterContentResolver.buildUserMessage(directory);

            ModelRequestContextHolder.setRequestSource("DOC_SUMMARY_MANUAL");
            String summary;
            try {
                summary = aiModelService.generateResponse(prompt, userMessage);
            } finally {
                ModelRequestContextHolder.clear();
            }

            if (summary != null && !summary.trim().isEmpty()) {
                logger.info("AI模型返回章节总结，长度: {}", summary.length());
                return summary.trim();
            }

            return null;

        } catch (Exception e) {
            logger.error("调用AI模型生成章节总结失败: chapterId={}", directory.getChapterId(), e);
            return null;
        }
    }

    /**
     * 获取配置文件的值
     */
    private String getConfigValue(String key, String defaultValue) {
        try {
            String value = environment.getProperty(key);
            return value != null ? value : defaultValue;
        } catch (Exception e) {
            logger.warn("获取配置值失败: key={}, 使用默认值: {}", key, defaultValue);
            return defaultValue;
        }
    }

    @PostMapping("/directory/process")
    @Operation(summary = "手动触发目录抽取", description = "为指定文件手动触发目录抽取和总结处理")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "处理开始"),
            @ApiResponse(responseCode = "404", description = "文件不存在"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> processDirectory(
            @Parameter(description = "文件ID", required = true)
            @RequestParam String file_id) {

        logger.info("手动触发目录抽取: fileId={}", file_id);

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

        try {
            // 检查文件是否存在
            java.util.Optional<com.zhpb.gdyd_zhpb_zgf.entity.mysql.File> fileOptional = fileRepository.findByFileId(file_id);
            if (!fileOptional.isPresent()) {
                result.put("code", 200);
                result.put("message", "文件不存在");
                return ResponseEntity.ok().body(result);
            }

            com.zhpb.gdyd_zhpb_zgf.entity.mysql.File file = fileOptional.get();

            // 获取文件的完整路径
            String filePath = constructFilePath(file);
            if (filePath == null) {
                result.put("code", 200);
                result.put("message", "文件路径不存在，无法找到文件：" + file.getFileName() +
                    "（fileId: " + file.getFileId() + "）");
                result.put("fileId", file_id);
                result.put("fileName", file.getFileName());
                result.put("storedPath", file.getFilePath());
                return ResponseEntity.ok().body(result);
            }

            // 异步处理文件目录
            try {
                java.lang.reflect.Method method = fileService.getClass().getDeclaredMethod("processFileDirectoriesAsync",
                    java.util.List.class, String.class);
                method.setAccessible(true);

                java.util.List<String> filePaths = java.util.Arrays.asList(filePath);
                method.invoke(fileService, filePaths, file.getProjectId());

                result.put("code", 0);
                result.put("message", "目录抽取任务已启动，请稍后查询");
                result.put("fileId", file_id);
                result.put("fileName", file.getFileName());

            } catch (Exception e) {
                logger.error("启动目录抽取任务失败", e);
                result.put("code", 500);
                result.put("message", "启动任务失败: " + e.getMessage());
                return ResponseEntity.internalServerError().body(result);
            }

        } catch (Exception e) {
            logger.error("手动触发目录抽取失败", e);
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 根据文件信息构造文件路径
     */
    private String constructFilePath(com.zhpb.gdyd_zhpb_zgf.entity.mysql.File file) {
        try {
            java.util.Optional<java.nio.file.Path> resolvedOpt = filePathResolver.resolveExistingPath(
                file.getFilePath(), file.getProjectId(), file.getFileName());
            if (resolvedOpt.isPresent()) {
                java.nio.file.Path resolvedPath = resolvedOpt.get();
                String normalized = filePathResolver.normalizeForStorage(resolvedPath);
                if (normalized != null && !normalized.equals(file.getFilePath())) {
                    file.setFilePath(normalized);
                    fileRepository.save(file);
                    logger.info("已自动纠正文件路径: {} -> {}", file.getFileId(), normalized);
                }
                return resolvedPath.toString();
            }
            logger.warn("无法解析文件路径: fileId={}, storedPath={}", file.getFileId(), file.getFilePath());
            return null;

        } catch (Exception e) {
            logger.error("构造文件路径失败: fileId={}", file.getFileId(), e);
        }
        return null;
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null) return "";
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex > 0 ? fileName.substring(lastDotIndex) : "";
    }

    /**
     * 构建目录树形结构
     */
    private List<SummaryResponse.DirectoryItem> buildDirectoryTree(List<FileDirectory> directories) {
        List<SummaryResponse.DirectoryItem> result = new ArrayList<>();

        // 获取顶级目录（没有父章节的）
        List<FileDirectory> rootDirectories = directories.stream()
            .filter(dir -> dir.getParentChapterId() == null || dir.getParentChapterId().isEmpty())
            .toList();

        for (FileDirectory rootDir : rootDirectories) {
            SummaryResponse.DirectoryItem item = convertToDirectoryItem(rootDir);
            item.setChildren(buildChildren(directories, rootDir.getChapterId()));
            result.add(item);
        }

        return result;
    }

    /**
     * 递归构建子目录
     */
    private List<SummaryResponse.DirectoryItem> buildChildren(List<FileDirectory> allDirectories, String parentChapterId) {
        List<SummaryResponse.DirectoryItem> children = new ArrayList<>();

        List<FileDirectory> childDirectories = allDirectories.stream()
            .filter(dir -> parentChapterId.equals(dir.getParentChapterId()))
            .toList();

        for (FileDirectory childDir : childDirectories) {
            SummaryResponse.DirectoryItem item = convertToDirectoryItem(childDir);
            item.setChildren(buildChildren(allDirectories, childDir.getChapterId()));
            children.add(item);
        }

        return children;
    }

    /**
     * 转换FileDirectory为DirectoryItem
     */
    private SummaryResponse.DirectoryItem convertToDirectoryItem(FileDirectory directory) {
        SummaryResponse.DirectoryItem item = new SummaryResponse.DirectoryItem();
        item.setChapterId(directory.getChapterId());
        item.setTitle(directory.getTitle());
        item.setPage(directory.getPage());
        item.setStartPage(directory.getStartPage());
        item.setEndPage(directory.getEndPage());
        item.setChildren(new ArrayList<>());
        return item;
    }

    @Autowired
    private com.zhpb.gdyd_zhpb_zgf.service.CatalogExtractionRetryService catalogExtractionRetryService;

    @PostMapping("/retry/failed")
    @Operation(summary = "重试所有失败任务", description = "重新处理所有目录抽取失败和向量化失败的文件")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "重试任务已启动"),
            @ApiResponse(responseCode = "500", description = "系统错误")
    })
    public ResponseEntity<Map<String, Object>> retryAllFailedTasks(
            @Parameter(description = "项目ID（可选，不传则处理所有项目）", required = false)
            @RequestParam(value = "project_id", required = false) String projectId) {

        logger.info("重试所有失败任务: projectId={}", projectId);

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

        try {
            int catalogRetryCount = 0;
            int vectorRetryCount = 0;

            // 1. 重试目录抽取失败的文件
            java.util.List<com.zhpb.gdyd_zhpb_zgf.entity.mysql.File> catalogFailedFiles;
            if (projectId != null && !projectId.isEmpty()) {
                catalogFailedFiles = fileRepository.findByProjectIdAndCatalogExtractionStatus(projectId, "failed");
            } else {
                catalogFailedFiles = fileRepository.findByCatalogExtractionStatus("failed");
            }

            for (com.zhpb.gdyd_zhpb_zgf.entity.mysql.File file : catalogFailedFiles) {
                file.setCatalogExtractionStatus("not_started");
                file.setCatalogExtractionRetryCount(0);
                fileRepository.save(file);
                catalogRetryCount++;
            }

            // 2. 重试向量化失败的文件
            java.util.List<com.zhpb.gdyd_zhpb_zgf.entity.mysql.File> vectorFailedFiles;
            if (projectId != null && !projectId.isEmpty()) {
                vectorFailedFiles = fileRepository.findByProjectIdAndVectorizationStatus(projectId, "failed");
            } else {
                vectorFailedFiles = fileRepository.findByVectorizationStatus("failed");
            }

            for (com.zhpb.gdyd_zhpb_zgf.entity.mysql.File file : vectorFailedFiles) {
                file.setVectorizationStatus("not_started");
                file.setIsVectorized(false);
                fileRepository.save(file);
                vectorRetryCount++;
            }

            // 3. 处理卡住的任务（processing 状态超过30分钟的）
            catalogExtractionRetryService.scanAndRetryStuckCatalogExtraction();

            result.put("code", 0);
            result.put("message", "重试任务已启动");
            result.put("catalogRetryCount", catalogRetryCount);
            result.put("vectorRetryCount", vectorRetryCount);
            result.put("projectId", projectId);

            logger.info("重试失败任务完成: 目录抽取重置{}个, 向量化重置{}个", catalogRetryCount, vectorRetryCount);

        } catch (Exception e) {
            logger.error("重试失败任务出错", e);
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }

        return ResponseEntity.ok(result);
    }

    @GetMapping("/status/failed")
    @Operation(summary = "查询失败任务数量", description = "查询目录抽取失败和向量化失败的文件数量")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    public ResponseEntity<Map<String, Object>> getFailedTasksStatus(
            @Parameter(description = "项目ID（可选，不传则查询所有项目）", required = false)
            @RequestParam(value = "project_id", required = false) String projectId) {

        logger.info("查询失败任务状态: projectId={}", projectId);

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

        try {
            long catalogFailedCount;
            long catalogProcessingCount;
            long vectorFailedCount;
            long vectorProcessingCount;

            if (projectId != null && !projectId.isEmpty()) {
                catalogFailedCount = fileRepository.countByProjectIdAndCatalogExtractionStatus(projectId, "failed");
                catalogProcessingCount = fileRepository.countByProjectIdAndCatalogExtractionStatus(projectId, "processing");
                vectorFailedCount = fileRepository.countByProjectIdAndVectorizationStatus(projectId, "failed");
                vectorProcessingCount = fileRepository.countByProjectIdAndVectorizationStatus(projectId, "processing");
            } else {
                catalogFailedCount = fileRepository.countByCatalogExtractionStatus("failed");
                catalogProcessingCount = fileRepository.countByCatalogExtractionStatus("processing");
                vectorFailedCount = fileRepository.countByVectorizationStatus("failed");
                vectorProcessingCount = fileRepository.countByVectorizationStatus("processing");
            }

            result.put("code", 0);
            result.put("message", "查询成功");
            result.put("projectId", projectId);
            result.put("catalogExtractionFailed", catalogFailedCount);
            result.put("catalogExtractionProcessing", catalogProcessingCount);
            result.put("vectorizationFailed", vectorFailedCount);
            result.put("vectorizationProcessing", vectorProcessingCount);

        } catch (Exception e) {
            logger.error("查询失败任务状态出错", e);
            result.put("code", 500);
            result.put("message", "系统错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }

        return ResponseEntity.ok(result);
    }
}
