"""
异步功能回归测试。
"""

from pathlib import Path

import pytest

from src.symphra_excel import Workbook
from src.symphra_excel.async_support import (
    AsyncBatchProcessor,
    AsyncWorkbook,
)


@pytest.mark.asyncio
async def test_async_workbook_create_and_save(tmp_path: Path) -> None:
    async_wb = AsyncWorkbook()
    await async_wb.create()
    sheet = await async_wb.create_worksheet("AsyncSheet")
    await sheet.set_cell_value("A1", "async value")

    output = tmp_path / "async.xlsx"
    await async_wb.save(output)
    await async_wb.close()

    loaded = Workbook.load(output)
    loaded_sheet = loaded.get_worksheet("AsyncSheet")
    assert loaded_sheet is not None
    assert loaded_sheet.get_cell_value("A1") == "async value"


@pytest.mark.asyncio
async def test_async_batch_processor(tmp_path: Path) -> None:
    file_paths: list[Path] = []
    for idx in range(3):
        wb = Workbook()
        sheet = wb.active
        sheet.set_cell_value("A1", idx)
        path = tmp_path / f"source_{idx}.xlsx"
        wb.save(path)
        file_paths.append(path)

    async_processor = AsyncBatchProcessor(max_workers=2)

    def process_func(workbook: Workbook, delta: int) -> int:
        sheet = workbook.active
        value = sheet.get_cell_value("A1") or 0
        return int(value) + delta

    results = await async_processor.process_multiple_files(file_paths, process_func, 5)
    await async_processor.close()

    assert sorted(results) == [5, 6, 7]
