/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.utils
 * @ClassName: PdfTableExtractor
 * @Description: PDF表格提取工具类 - 使用tabula-java提取PDF中的表格并转换为结构化文本
 * @Author: 张志锋
 * @Date: 2025-12-11
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import technology.tabula.ObjectExtractor;
import technology.tabula.Page;
import technology.tabula.PageIterator;
import technology.tabula.Table;
import technology.tabula.RectangularTextContainer;
import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF表格提取工具类
 * 将PDF中的表格转换为易于向量化的自然语言格式
 */
public class PdfTableExtractor {

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

    /**
     * 从PDF中提取表格并转换为自然语言描述
     *
     * @param filePath PDF文件路径
     * @return 表格的自然语言描述，如果没有表格则返回null
     */
    public static String extractTablesAsText(String filePath) {
        StringBuilder result = new StringBuilder();
        int tableCount = 0;

        try (PDDocument document = org.apache.pdfbox.Loader.loadPDF(new File(filePath))) {
            SpreadsheetExtractionAlgorithm algorithm = new SpreadsheetExtractionAlgorithm();
            
            try (ObjectExtractor extractor = new ObjectExtractor(document)) {
                PageIterator pages = extractor.extract();
                
                while (pages.hasNext()) {
                    Page page = pages.next();
                    List<Table> tables = algorithm.extract(page);
                    
                    for (Table table : tables) {
                        if (table.getRowCount() < 2) {
                            continue; // 跳过只有一行的表格（可能只是表头）
                        }
                        
                        tableCount++;
                        String tableText = convertTableToText(table, tableCount);
                        if (tableText != null && !tableText.isBlank()) {
                            result.append(tableText).append("\n\n");
                        }
                    }
                }
            }
            
            if (tableCount > 0) {
                logger.info("[表格提取] 从PDF中提取了 {} 个表格", tableCount);
            } else {
                logger.debug("[表格提取] PDF中未检测到表格");
            }
            
        } catch (Exception e) {
            logger.warn("[表格提取] 提取表格失败: {}", e.getMessage());
        }

        return result.length() > 0 ? result.toString() : null;
    }

    /**
     * 将单个表格转换为自然语言描述
     */
    private static String convertTableToText(Table table, int tableIndex) {
        StringBuilder sb = new StringBuilder();
        
        List<List<RectangularTextContainer>> rows = table.getRows();
        if (rows.isEmpty()) {
            return null;
        }
        
        // 获取表头
        List<String> headers = new ArrayList<>();
        if (!rows.isEmpty()) {
            for (RectangularTextContainer cell : rows.get(0)) {
                String text = cell.getText().trim().replaceAll("\\s+", " ");
                headers.add(text.isEmpty() ? "列" + (headers.size() + 1) : text);
            }
        }
        
        // 如果表头看起来不像表头（全是数字或空），尝试生成通用表头
        boolean hasValidHeaders = headers.stream().anyMatch(h -> h.length() > 0 && !h.matches("\\d+"));
        
        // 处理数据行（从第2行开始，如果有有效表头的话）
        int startRow = hasValidHeaders ? 1 : 0;
        int rowNum = 0;
        
        for (int i = startRow; i < rows.size(); i++) {
            List<RectangularTextContainer> row = rows.get(i);
            rowNum++;
            
            // 构建该行的自然语言描述
            StringBuilder rowDesc = new StringBuilder();
            rowDesc.append("第").append(rowNum).append("项: ");
            
            List<String> items = new ArrayList<>();
            for (int j = 0; j < row.size() && j < headers.size(); j++) {
                String cellText = row.get(j).getText().trim().replaceAll("\\s+", " ");
                if (!cellText.isEmpty()) {
                    String header = j < headers.size() ? headers.get(j) : "字段" + (j + 1);
                    items.add(header + "为\"" + cellText + "\"");
                }
            }
            
            if (!items.isEmpty()) {
                rowDesc.append(String.join("，", items));
                sb.append(rowDesc).append("。\n");
            }
        }
        
        if (sb.length() == 0) {
            return null;
        }
        
        // 添加表格标题
        StringBuilder result = new StringBuilder();
        result.append("【表格").append(tableIndex).append("】\n");
        result.append(sb);
        
        return result.toString();
    }

    /**
     * 提取表格并合并到原有文本中
     *
     * @param filePath PDF文件路径
     * @param originalText 原有的PDF文本内容
     * @return 合并后的文本（表格内容追加在后面）
     */
    public static String enhanceTextWithTables(String filePath, String originalText) {
        String tableText = extractTablesAsText(filePath);
        
        if (tableText == null || tableText.isBlank()) {
            return originalText;
        }
        
        StringBuilder enhanced = new StringBuilder();
        enhanced.append(originalText);
        enhanced.append("\n\n=== 表格结构化内容 ===\n\n");
        enhanced.append(tableText);
        
        return enhanced.toString();
    }
}
