package com.zhpb.gdyd_zhpb_zgf.service;

import com.zhpb.gdyd_zhpb_zgf.entity.mysql.File;
import com.zhpb.gdyd_zhpb_zgf.entity.mysql.FileDirectory;
import com.zhpb.gdyd_zhpb_zgf.entity.pgsql.PdfVector;
import com.zhpb.gdyd_zhpb_zgf.repository.mysql.FileRepository;
import com.zhpb.gdyd_zhpb_zgf.repository.pgsql.PdfVectorRepository;
import com.zhpb.gdyd_zhpb_zgf.service.FilePathResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.nio.file.Path;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 章节内容解析组件，统一从向量数据库中读取章节正文并构建用户提示。
 * 优化：使用PdfContentCache避免重复读取PDF文件
 */
@Service
public class ChapterContentResolver {

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

    private static final int MAX_SEGMENTS = 5;
    private static final int MAX_CONTENT_LENGTH = 2000;

    private final PdfVectorRepository pdfVectorRepository;
    private final FileRepository fileRepository;
    private final FilePathResolver filePathResolver;
    private final PdfContentCache pdfContentCache;

    public ChapterContentResolver(PdfVectorRepository pdfVectorRepository,
                                  FileRepository fileRepository,
                                  FilePathResolver filePathResolver,
                                  PdfContentCache pdfContentCache) {
        this.pdfVectorRepository = pdfVectorRepository;
        this.fileRepository = fileRepository;
        this.filePathResolver = filePathResolver;
        this.pdfContentCache = pdfContentCache;
    }

    /**
     * 根据章节目录信息构建发送给大模型的 user 消息。
     */
    public String buildUserMessage(FileDirectory directory) {
        String title = directory != null && StringUtils.hasText(directory.getTitle())
            ? directory.getTitle().trim()
            : "未命名章节";
        String resolvedContent = resolveChapterContent(directory);
        if (!StringUtils.hasText(resolvedContent)) {
            resolvedContent = "未能提取该章节正文，请参考原始文档。";
        }
        return "章节标题：" + title + "\n章节内容：\n" + resolvedContent;
    }

    /**
     * 从向量库中拼接章节正文。
     */
    public String resolveChapterContent(FileDirectory directory) {
        if (directory == null || !StringUtils.hasText(directory.getFileId())) {
            return "";
        }
        List<PdfVector> vectors = pdfVectorRepository.findByFileId(directory.getFileId());
        if (CollectionUtils.isEmpty(vectors)) {
            return loadContentFromDisk(directory);
        }
        String merged = vectors.stream()
            .sorted(Comparator.comparing(PdfVector::getId))
            .map(PdfVector::getContent)
            .filter(Objects::nonNull)
            .map(String::trim)
            .filter(StringUtils::hasText)
            .limit(MAX_SEGMENTS)
            .collect(Collectors.joining("\n\n"));

        if (!StringUtils.hasText(merged)) {
            return "";
        }
        if (merged.length() <= MAX_CONTENT_LENGTH) {
            return merged;
        }
        return merged.substring(0, MAX_CONTENT_LENGTH) + "……（正文已截断）";
    }

    /**
     * 当向量库没有内容时，降级从原始PDF读取文本（使用缓存）
     */
    private String loadContentFromDisk(FileDirectory directory) {
        try {
            Optional<File> fileOpt = fileRepository.findByFileId(directory.getFileId());
            if (fileOpt.isEmpty()) {
                return "";
            }
            File file = fileOpt.get();
            Optional<Path> resolvedPath = filePathResolver.resolveExistingPath(
                file.getFilePath(), file.getProjectId(), file.getFileName());
            if (resolvedPath.isEmpty()) {
                return "";
            }
            
            // 使用缓存读取PDF内容（优化：避免重复打开PDF文件）
            String fullContent = pdfContentCache.getFullContent(resolvedPath.get().toString(), 5);
            
            if (!StringUtils.hasText(fullContent)) {
                return "";
            }
            
            fullContent = fullContent.trim();
            if (fullContent.length() > MAX_CONTENT_LENGTH) {
                return fullContent.substring(0, MAX_CONTENT_LENGTH) + "……（正文已截断）";
            }
            return fullContent;
            
        } catch (Exception e) {
            logger.warn("降级读取PDF正文失败: fileId={}, error={}", directory.getFileId(), e.getMessage());
            return "";
        }
    }
}


