/*
 *  Copyright (c) 2023-2026, Easy-Agents (fuhai999@gmail.com).
 *  <p>
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  <p>
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  <p>
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.easyagents.core.file2text.extractor.impl;


import com.easyagents.core.file2text.DocumentReadErrorCode;
import com.easyagents.core.file2text.DocumentReadException;
import com.easyagents.core.file2text.DocumentReadSupport;
import com.easyagents.core.file2text.DocumentTextSegment;
import com.easyagents.core.file2text.LightweightDocumentReadRequest;
import com.easyagents.core.file2text.LightweightDocumentReadResult;
import com.easyagents.core.file2text.extractor.FileExtractor;
import com.easyagents.core.file2text.source.DocumentSource;
import org.apache.poi.xwpf.usermodel.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * DOCX 文档提取器（.docx, .dotx）
 * 支持段落、表格、列表文本提取
 */
public class DocxExtractor implements FileExtractor {

    private static final Set<String> KNOWN_MIME_TYPES;
    private static final String MIME_PREFIX = "application/vnd.openxmlformats-officedocument.wordprocessingml";
    private static final Set<String> SUPPORTED_EXTENSIONS;

    static {
        // 精确 MIME（可选）
        Set<String> mimeTypes = new HashSet<>();
        mimeTypes.add("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        KNOWN_MIME_TYPES = Collections.unmodifiableSet(mimeTypes);

        // 支持的扩展名
        Set<String> extensions = new HashSet<>();
        extensions.add("docx");
        extensions.add("dotx");
        SUPPORTED_EXTENSIONS = Collections.unmodifiableSet(extensions);
    }

    @Override
    public boolean supports(DocumentSource source) {
        String mimeType = source.getMimeType();
        String fileName = source.getFileName();

        // 1. MIME 精确匹配
        if (mimeType != null && KNOWN_MIME_TYPES.contains(mimeType)) {
            return true;
        }

        // 2. MIME 前缀匹配
        if (mimeType != null && mimeType.startsWith(MIME_PREFIX)) {
            return true;
        }

        // 3. 扩展名匹配
        if (fileName != null) {
            String ext = getExtension(fileName);
            if (ext != null && SUPPORTED_EXTENSIONS.contains(ext.toLowerCase())) {
                return true;
            }
        }

        return false;
    }

    @Override
    public String extractText(DocumentSource source) throws IOException {
        return read(new LightweightDocumentReadRequest(source)).getText();
    }

    /**
     * 按正文顺序读取 DOCX 段落和表格。
     *
     * @param request 读取请求
     * @return 结构化读取结果
     * @throws IOException 文档 I/O 失败
     */
    @Override
    public LightweightDocumentReadResult read(LightweightDocumentReadRequest request) throws IOException {
        DocumentSource source = request.getSource();
        try (InputStream is = source.openStream();
             XWPFDocument document = new XWPFDocument(is)) {
            List<DocumentTextSegment> segments = new ArrayList<>();
            List<String> headingPath = new ArrayList<>();
            int paragraphIndex = 0;
            int tableIndex = 0;
            int offset = 0;
            for (IBodyElement element : document.getBodyElements()) {
                request.checkCancelled();
                if (element instanceof XWPFParagraph paragraph) {
                    paragraphIndex++;
                    String text = getParagraphText(paragraph);
                    if (text == null || text.isBlank()) {
                        continue;
                    }
                    int headingLevel = headingLevel(paragraph);
                    if (headingLevel > 0) {
                        while (headingPath.size() >= headingLevel) {
                            headingPath.remove(headingPath.size() - 1);
                        }
                        headingPath.add(text.trim());
                    }
                    DocumentTextSegment segment = DocumentReadSupport.segment(
                            "paragraph-" + paragraphIndex, text, "PARAGRAPH",
                            "第 " + paragraphIndex + " 段", offset, headingPath);
                    segments.add(segment);
                    offset = segment.getEndIndex() + 1;
                } else if (element instanceof XWPFTable table) {
                    tableIndex++;
                    String tableText = getTableText(table);
                    if (tableText.isBlank()) {
                        continue;
                    }
                    DocumentTextSegment segment = DocumentReadSupport.segment(
                            "table-" + tableIndex, tableText, "TABLE",
                            "第 " + tableIndex + " 个表格", offset, headingPath);
                    segments.add(segment);
                    offset = segment.getEndIndex() + 1;
                }
            }
            return DocumentReadSupport.result(source, segments, request);
        } catch (DocumentReadException e) {
            throw e;
        } catch (Exception e) {
            throw new DocumentReadException(DocumentReadErrorCode.DOCUMENT_CORRUPTED,
                    "Failed to extract DOCX", e);
        }
    }

    private String getParagraphText(XWPFParagraph paragraph) {
        StringBuilder text = new StringBuilder();
        for (XWPFRun run : paragraph.getRuns()) {
            String runText = run.text();
            if (runText != null) {
                text.append(runText);
            }
        }
        return text.length() > 0 ? text.toString() : null;
    }

    private String getCellText(XWPFTableCell cell) {
        String simpleText = cell.getText();
        if (simpleText != null && !simpleText.isEmpty()) {
            return simpleText;
        }
        StringBuilder text = new StringBuilder();
        for (XWPFParagraph p : cell.getParagraphs()) {
            String pt = getParagraphText(p);
            if (pt != null) {
                text.append(pt).append(" ");
            }
        }
        return text.toString().trim();
    }

    /**
     * 获取表格的显示文本。
     *
     * @param table 表格
     * @return 表格文本
     */
    private String getTableText(XWPFTable table) {
        StringBuilder text = new StringBuilder();
        for (XWPFTableRow row : table.getRows()) {
            List<String> cellTexts = row.getTableCells().stream()
                    .map(this::getCellText)
                    .map(String::trim)
                    .collect(Collectors.toList());
            if (cellTexts.stream().anyMatch(item -> !item.isEmpty())) {
                text.append(String.join(" | ", cellTexts)).append('\n');
            }
        }
        return text.toString().trim();
    }

    /**
     * 解析常见 Word 标题样式层级。
     *
     * @param paragraph 段落
     * @return 标题层级，非标题返回 0
     */
    private int headingLevel(XWPFParagraph paragraph) {
        String style = paragraph.getStyle();
        if (style == null) {
            return 0;
        }
        String normalized = style.replaceAll("\\s+", "").toLowerCase();
        if (!normalized.startsWith("heading") && !normalized.startsWith("标题")) {
            return 0;
        }
        String digits = normalized.replaceAll("\\D+", "");
        if (digits.isEmpty()) {
            return 1;
        }
        try {
            return Math.max(1, Math.min(9, Integer.parseInt(digits)));
        } catch (NumberFormatException ignored) {
            return 1;
        }
    }

    @Override
    public int getOrder() {
        return 10;
    }

    private String getExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) return null;
        int lastDot = fileName.lastIndexOf('.');
        return fileName.substring(lastDot + 1);
    }
}
