package com.emoon.knowledge.chain.loader;

import com.emoon.knowledge.chain.split.TextSplitter;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Excel 文件加载器（自动识别 xls/xlsx）
 * 对应原 org.ruoyi.chain.loader.ExcelFileLoader 的能力迁移
 */
@Component
@AllArgsConstructor
@Slf4j
public class ExcelFileLoader implements ResourceLoader {

    private final TextSplitter textSplitter;

    @Override
    public String getContent(InputStream inputStream) {
        StringBuilder sb = new StringBuilder();
        try {
            // 使用带有 mark/reset 的流以便做魔数检测
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            bis.mark(16);
            FileMagic fileMagic = FileMagic.valueOf(bis);
            Workbook workbook;
            if (fileMagic == FileMagic.OLE2) {
                workbook = new HSSFWorkbook(bis);
            } else if (fileMagic == FileMagic.OOXML) {
                workbook = new XSSFWorkbook(bis);
            } else {
                // 兜底：交给 WorkbookFactory 自动识别
                workbook = WorkbookFactory.create(bis);
            }

            try (workbook) {
                // 默认读取第一个sheet，可以根据需要循环所有sheet
                Sheet sheet = workbook.getSheetAt(0);
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        sb.append(getCellValue(cell)).append(" ");
                    }
                    sb.append("\n");
                }
            }
        } catch (EncryptedDocumentException e) {
            log.error("读取Excel失败：文件被加密", e);
            throw new RuntimeException("读取Excel失败：文件被加密，请提供未加密文件", e);
        } catch (IOException e) {
            log.error("读取Excel失败", e);
            throw new RuntimeException("读取Excel失败：可能是文件损坏或格式不匹配(.xls/.xlsx)", e);
        }
        return sb.toString();
    }

    @Override
    public List<String> getChunkList(String content, String kid) {
        return textSplitter.split(content, kid);
    }

    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                }
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }
}
