package top.r3944realms.docchecktoolrefactored.io.reader;

import com.linuxense.javadbf.DBFReader;
import com.linuxense.javadbf.DBFRow;
import lombok.extern.slf4j.Slf4j;
import top.r3944realms.docchecktoolrefactored.core.LogicalAddressFileGenerator;
import top.r3944realms.docchecktoolrefactored.util.FileUtil;
import top.r3944realms.docchecktoolrefactored.util.LoggerMarker;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * DBF文件读取器实现
 */
@Slf4j
public class DbfFileReader implements CatalogFileReader {
    // 常量定义（避免硬编码）
    private static final List<String> ARCHIVE_CODE_TAG_CANDIDATES =
            Arrays.asList("档号", "dangan", "fileNo", "DH");

    private static final List<String> PAGE_COUNT_TAG_CANDIDATES =
            Arrays.asList("页数", "pages", "pageCount", "YS");

    @Override
    public List<LogicalAddressFileGenerator.Record> readCatalogFile(String filePath) throws Exception {

        List<LogicalAddressFileGenerator.Record> records = new ArrayList<>();
        File file = FileUtil.fileCheckAndGet(filePath, "dbf");
        try (
            FileInputStream fis = new FileInputStream(file);
            DBFReader reader = new DBFReader(fis)
        ) {
            int fieldCount = reader.getFieldCount();
            log.debug(LoggerMarker.DEBUG_MARKER, "开始读取DBF文件: {}, DBF文件字段数: {}",filePath, fieldCount);

            // 查找"档号"和"页数"字段的索引
            int archiveCodeIndex = -1;
            int pageIndex = -1;
            for (int i = 0; i < fieldCount; i++) {
                if (archiveCodeIndex != -1 && pageIndex != -1) {
                    log.debug(LoggerMarker.DEBUG_MARKER, "已找到所需字段，跳出循环，档号: {}, 页数: {}", archiveCodeIndex, pageIndex);
                    break;
                }
                String fieldName = reader.getField(i).getName();
                log.debug(LoggerMarker.DEBUG_MARKER, "发现字段: {}", fieldName);
                if (ARCHIVE_CODE_TAG_CANDIDATES.contains(fieldName)) {
                    archiveCodeIndex = i;
                    log.debug(LoggerMarker.DEBUG_MARKER, "匹配到档号字段: {}, 索引: {}", fieldName, archiveCodeIndex);
                } else if (PAGE_COUNT_TAG_CANDIDATES.contains(fieldName)) {
                    pageIndex = i;
                    log.debug(LoggerMarker.DEBUG_MARKER, "匹配到页数字段: {}, 索引: {}", fieldName, pageIndex);
                }

            }
            if (archiveCodeIndex == -1 || pageIndex == -1) {
                log.error(LoggerMarker.RELEASE_MARKER, "未找到必要字段，档号: {}, 页数: {}",
                        archiveCodeIndex == -1 ? "未找到" : archiveCodeIndex,
                        pageIndex == -1 ? "未找到" : pageIndex
                );
                throw new IllegalArgumentException(
                        String.format("DBF文件缺少必要字段: 档号=%s, 页数=%s",
                                archiveCodeIndex == -1, pageIndex == -1
                        )
                );
            }
            int validRecords = 0;
            int skippedRecords = 0;
            DBFRow row;
            while ((row = reader.nextRow()) != null) {
                String archiveCode =
                        Optional.ofNullable(row.getObject(archiveCodeIndex))
                                .map(Object::toString)
                                .map(String::trim)
                                .orElse("");
                int page =
                        Optional.ofNullable(row.getObject(pageIndex))
                                .map(i -> {
                                    try {
                                        if (i instanceof Number) {
                                            return ((Number) i).intValue();
                                        } else {
                                            return Integer.parseInt(i.toString().trim());
                                        }
                                    } catch (NumberFormatException e) {
                                        log.warn(LoggerMarker.DEBUG_MARKER, "无法将页数值转换为整数: {}", i);
                                        return 0;
                                    }
                                }).orElse(0);

                // 只有当档号不为空且页数大于0时才添加记录
                if (!archiveCode.isEmpty() && page > 0) {
                    records.add(new LogicalAddressFileGenerator.Record(archiveCode, page));
                    validRecords++;
                    log.debug(LoggerMarker.DEBUG_MARKER, "读取有效记录 - 档号: {}, 页数: {}", archiveCode, page);
                } else {
                    skippedRecords++;
                    if (!archiveCode.isEmpty() || page > 0) {
                        log.debug(LoggerMarker.DEBUG_MARKER, "跳过无效记录 - 档号: {}, 页数: {}", archiveCode, page);
                    }
                }
            }
            log.info(LoggerMarker.RELEASE_MARKER, "DBF文件读取完成，有效记录: {} 条，跳过记录: {} 条", validRecords, skippedRecords);
        } catch (IOException e) {
            log.error(LoggerMarker.RELEASE_MARKER, "读取DBF文件失败: {}", filePath, e);
            throw new UncheckedIOException("DBF文件读取异常", e);
        }
        return records;
    }
}
