/*
 *  Copyright (c) 2023-2026, Easy-Agents (fuhai999@gmail.com).
 *  <p>
 *  Licensed under the Apache License, Version 2.0.
 */
package com.easyagents.core.file2text.extractor.impl;

import com.easyagents.core.file2text.DocumentReadSupport;
import com.easyagents.core.file2text.DocumentTextSegment;

import java.util.ArrayList;
import java.util.List;

/**
 * 表格行到稳定片段的内部转换工具。
 */
final class SpreadsheetReadSupport {

    private static final int ROWS_PER_SEGMENT = 25;

    private SpreadsheetReadSupport() {
    }

    /**
     * 将工作表行按固定区间组成片段。
     *
     * @param sheets 工作表数据
     * @return 文本片段
     */
    static List<DocumentTextSegment> toSegments(List<SheetRows> sheets) {
        List<DocumentTextSegment> segments = new ArrayList<>();
        int offset = 0;
        for (SheetRows sheet : sheets) {
            for (int start = 0; start < sheet.rows().size(); start += ROWS_PER_SEGMENT) {
                int end = Math.min(sheet.rows().size(), start + ROWS_PER_SEGMENT);
                List<RowText> rows = sheet.rows().subList(start, end);
                StringBuilder text = new StringBuilder();
                for (RowText row : rows) {
                    if (!text.isEmpty()) {
                        text.append('\n');
                    }
                    text.append("第 ").append(row.rowNumber()).append(" 行: ").append(row.text());
                }
                int startRow = rows.get(0).rowNumber();
                int endRow = rows.get(rows.size() - 1).rowNumber();
                DocumentTextSegment segment = DocumentReadSupport.segment(
                        "sheet-" + sheet.sheetIndex() + "-rows-" + startRow + "-" + endRow,
                        text.toString(), "SHEET_ROW_RANGE",
                        sheet.sheetName() + " 第 " + startRow + "-" + endRow + " 行",
                        offset, List.of(sheet.sheetName()));
                segments.add(segment);
                offset = segment.getEndIndex() + 1;
            }
        }
        return segments;
    }

    /**
     * 单个工作表的有效行。
     *
     * @param sheetIndex 工作表序号
     * @param sheetName 工作表名
     * @param rows 有效行
     */
    record SheetRows(int sheetIndex, String sheetName, List<RowText> rows) {
    }

    /**
     * 单行格式化文本。
     *
     * @param rowNumber 行号
     * @param text 文本
     */
    record RowText(int rowNumber, String text) {
    }
}
