from io import BytesIO

from openpyxl import Workbook, load_workbook

from app.services.agent_asset_spreadsheet import AgentAssetSpreadsheetManager


def test_rebuild_from_uploaded_content_preserves_sheet_values() -> None:
    source = Workbook()
    first = source.active
    first.title = "差旅标准"
    first.append(["城市", "住宿费"])
    first.append(["北京", 500])
    second = source.create_sheet("补贴标准")
    second.append(["区域", "餐补"])
    second.append(["直辖市", 75])

    source_buffer = BytesIO()
    source.save(source_buffer)

    rebuilt = AgentAssetSpreadsheetManager.rebuild_from_uploaded_content(
        source_buffer.getvalue()
    )
    workbook = load_workbook(BytesIO(rebuilt), data_only=False)

    assert workbook.sheetnames == ["差旅标准", "补贴标准"]
    assert workbook["差旅标准"]["A2"].value == "北京"
    assert workbook["差旅标准"]["B2"].value == 500
    assert workbook["补贴标准"]["A2"].value == "直辖市"
    assert workbook["补贴标准"]["B2"].value == 75


def build_workbook_bytes(rows: list[list[object]], *, sheet_name: str = "规则表") -> bytes:
    workbook = Workbook()
    sheet = workbook.active
    sheet.title = sheet_name
    for row in rows:
        sheet.append(row)
    buffer = BytesIO()
    workbook.save(buffer)
    return buffer.getvalue()
