r"""
Pandas Excel reader - Convenience functions wrapping pd.read_excel.

Provides:
- read_excel: Read a single sheet as DataFrame
- read_excel_all_sheets: Read all sheets as dict[str, DataFrame]

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 read_excel(
    path: Path | str,
    sheet_name: str | int = 0,
    **kwargs: Any,
) -> pd.DataFrame:
    """
    Read a single Excel sheet into a pandas DataFrame.

    Args:
        path: Path to the Excel file (.xlsx, .xls).
        sheet_name: Sheet to read. 0-based index (int) or sheet name (str). Default: first sheet.
        **kwargs: Passed through to pandas.read_excel (e.g., header, usecols, dtype).

    Returns:
        DataFrame containing the sheet data.

    Raises:
        ExcelError: If file not found or read fails.

    Example:
        df = read_excel("data.xlsx")
        df = read_excel("data.xlsx", sheet_name="Sales", header=1)
        df = read_excel("data.xlsx", usecols="A:C", dtype={"ID": str})
    """
    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)
    if not p.exists():
        raise ExcelError(f"Excel file not found: {p}")
    try:
        return pd.read_excel(p, sheet_name=sheet_name, engine="openpyxl", **kwargs)
    except Exception as e:
        raise ExcelError(f"Failed to read Excel file: {p}") from e


def read_excel_all_sheets(
    path: Path | str,
    **kwargs: Any,
) -> dict[str, pd.DataFrame]:
    """
    Read all Excel sheets into a dict of DataFrames.

    Args:
        path: Path to the Excel file (.xlsx, .xls).
        **kwargs: Passed through to pandas.read_excel (e.g., header, usecols).

    Returns:
        Dict mapping sheet name to DataFrame.

    Raises:
        ExcelError: If file not found or read fails.

    Example:
        sheets = read_excel_all_sheets("workbook.xlsx")
        sales_df = sheets["Sales"]
    """
    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)
    if not p.exists():
        raise ExcelError(f"Excel file not found: {p}")
    try:
        return pd.read_excel(
            p,
            sheet_name=None,
            engine="openpyxl",
            **kwargs,
        )
    except Exception as e:
        raise ExcelError(f"Failed to read Excel file: {p}") from e
