"""Excel export helpers."""
from __future__ import annotations

import io
from typing import Any, Optional

import pandas as pd


def to_excel_bytes(
    results_df: pd.DataFrame,
    stats: dict[str, Any],
    prompt_info: dict[str, Any],
    original_data_df: pd.DataFrame,
    template_schema: Optional[pd.DataFrame] = None,
) -> bytes:
    """Create a multi-sheet Excel workbook and return as bytes."""
    buf = io.BytesIO()
    with pd.ExcelWriter(buf, engine="xlsxwriter") as xw:
        (results_df if results_df is not None else pd.DataFrame()).to_excel(
            xw, index=False, sheet_name="Indexing Results"
        )
        (original_data_df if original_data_df is not None else pd.DataFrame()).to_excel(
            xw, index=False, sheet_name="Original Data"
        )
        pd.DataFrame([stats]).to_excel(xw, index=False, sheet_name="Statistics")
        pd.DataFrame([prompt_info]).to_excel(xw, index=False, sheet_name="Configuration")
        if template_schema is not None and not template_schema.empty:
            template_schema.to_excel(xw, index=False, sheet_name="Template Schema")
    buf.seek(0)
    return buf.getvalue()
