package com.lingyue.parse.service;

import com.lingyue.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Word文档文本提取服务
 * 支持.docx和.doc格式
 * 
 * @author lingyue
 * @since 2026-01-14
 */
@Slf4j
@Service
public class WordTextExtractionService {
    
    /**
     * 提取Word文档文本
     * 
     * @param wordFilePath Word文件路径
     * @return 提取的文本内容
     */
    public String extractText(String wordFilePath) {
        File wordFile = new File(wordFilePath);
        if (!wordFile.exists()) {
            throw new ServiceException("Word文件不存在: " + wordFilePath);
        }
        
        String fileName = wordFile.getName().toLowerCase();
        
        try {
            if (fileName.endsWith(".docx")) {
                return extractFromDocx(wordFilePath);
            } else if (fileName.endsWith(".doc")) {
                return extractFromDoc(wordFilePath);
            } else {
                throw new ServiceException("不支持的Word文件格式: " + fileName);
            }
        } catch (IOException e) {
            log.error("提取Word文档文本失败: {}", wordFilePath, e);
            throw new ServiceException("提取Word文档文本失败: " + e.getMessage());
        }
    }
    
    /**
     * 从.docx文件提取文本
     */
    private String extractFromDocx(String filePath) throws IOException {
        log.info("提取.docx文件文本: {}", filePath);
        
        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
            
            String text = extractor.getText();
            log.debug("提取到文本长度: {}", text != null ? text.length() : 0);
            return text != null ? text : "";
        }
    }
    
    /**
     * 从.doc文件提取文本
     */
    private String extractFromDoc(String filePath) throws IOException {
        log.info("提取.doc文件文本: {}", filePath);
        
        try (FileInputStream fis = new FileInputStream(filePath);
             HWPFDocument document = new HWPFDocument(fis);
             WordExtractor extractor = new WordExtractor(document)) {
            
            String text = extractor.getText();
            log.debug("提取到文本长度: {}", text != null ? text.length() : 0);
            return text != null ? text : "";
        }
    }
}
