r"""
Pandas Excel writer - Convenience functions wrapping DataFrame.to_excel.

Provides:
- write_excel: Write a single DataFrame to an Excel sheet
- write_excel_sheets: Write multiple DataFrames to separate sheets

Requires: pip install yclibs[excel]
"""

from __future__ import annotations

import logging
from pathlib import Path
from typing import TYPE_CHECKING, Any

from yclibs.excel.reader import ExcelError

logger = logging.getLogger(__name__)

if TYPE_CHECKING:
    import pandas as pd


def write_excel(
    data: pd.DataFrame,
    path: Path | str,
    sheet_name: str = "Sheet1",
    *,
    mode: str = "w",
    **kwargs: Any,
) -> Path:
    """
    Write a DataFrame to an Excel file.

    Args:
        data: DataFrame to write.
        path: Path to the output Excel file (.xlsx).
        sheet_name: Name of the sheet. Default: "Sheet1".
        mode: Write mode. "w" to overwrite (default), "a" to append to existing file.
        **kwargs: Passed through to DataFrame.to_excel (e.g., index, header, startrow).

    Returns:
        Path to the saved file.

    Raises:
        ExcelError: If write fails.

    Example:
        write_excel(df, "output.xlsx")
        write_excel(df, "output.xlsx", sheet_name="Sales", index=False)
        write_excel(df, "existing.xlsx", mode="a", sheet_name="Report")
    """
    try:
        import pandas as pd  # noqa: PLC0415
    except ImportError as e:
        msg = "pandas is required. Install with: pip install yclibs[excel]"
        raise ExcelError(msg) from e
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    try:
        with pd.ExcelWriter(p, engine="openpyxl", mode=mode) as writer:
            data.to_excel(writer, sheet_name=sheet_name, **kwargs)
    except Exception as e:
        raise ExcelError(f"Failed to write Excel file: {p}") from e
    logger.debug("Wrote DataFrame to %s", p)
    return p


def write_excel_sheets(
    data: dict[str, pd.DataFrame],
    path: Path | str,
    *,
    mode: str = "w",
    **kwargs: Any,
) -> Path:
    """
    Write multiple DataFrames to an Excel file, each as a separate sheet.

    Args:
        data: Dict mapping sheet name to DataFrame.
        path: Path to the output Excel file (.xlsx).
        mode: Write mode. "w" to overwrite (default), "a" to append.
        **kwargs: Passed through to DataFrame.to_excel for each sheet (e.g., index, header).

    Returns:
        Path to the saved file.

    Raises:
        ExcelError: If write fails.

    Example:
        write_excel_sheets({"Sales": sales_df, "Summary": summary_df}, "report.xlsx")
    """
    try:
        import pandas as pd  # noqa: PLC0415
    except ImportError as e:
        msg = "pandas is required. Install with: pip install yclibs[excel]"
        raise ExcelError(msg) from e
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    try:
        with pd.ExcelWriter(p, engine="openpyxl", mode=mode) as writer:
            for sheet_name, df in data.items():
                df.to_excel(writer, sheet_name=sheet_name, **kwargs)
    except Exception as e:
        raise ExcelError(f"Failed to write Excel file: {p}") from e
    logger.debug("Wrote %d sheet(s) to %s", len(data), p)
    return p
