"""Matplotlib bar plot utilities with Chinese font support."""

from pathlib import Path
from typing import Any

from matplotlib.axes import Axes
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

from yclibs.matplotlib.utils import apply_chinese_font, setup_chinese_font


def bar_plot(
    categories: list[str],
    values: list[float],
    *,
    title: str = "",
    xlabel: str = "",
    ylabel: str = "",
    color: str | None = None,
    figsize: tuple[float, float] = (8, 5),
    font_path: str | Path | None = None,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Create a bar plot with optional Chinese font support.

    Args:
        categories: Category labels for the x-axis.
        values: Numeric values for bar heights.
        title: Plot title.
        xlabel: X-axis label.
        ylabel: Y-axis label.
        color: Single color or bar color. If None, uses default palette.
        figsize: Figure size (width, height).
        font_path: Path to Chinese font file or directory. If provided, finds, registers and applies it.
        **kwargs: Extra arguments passed to axes.bar() (e.g. edgecolor). Use
            x_tick_rotation to rotate x-tick labels (default 0).

    Returns:
        Tuple of (Figure, Axes).
    """
    if len(categories) != len(values):
        raise ValueError("categories and values must have the same length")

    font_family = setup_chinese_font(font_path) if font_path is not None else None

    fig, ax = plt.subplots(figsize=figsize)
    bar_kwargs: dict[str, Any] = dict(kwargs)
    if color is not None:
        bar_kwargs["color"] = color
    x_tick_rotation = bar_kwargs.pop("x_tick_rotation", 0)
    ax.bar(categories, values, **bar_kwargs)
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.tick_params(axis="x", rotation=x_tick_rotation)

    if font_family:
        apply_chinese_font(font_family, axes=ax)

    plt.tight_layout()
    return fig, ax


def horizontal_bar_plot(
    categories: list[str],
    values: list[float],
    *,
    title: str = "",
    xlabel: str = "",
    ylabel: str = "",
    color: str | None = None,
    figsize: tuple[float, float] = (8, 5),
    font_path: str | Path | None = None,
    **kwargs: Any,
) -> tuple[Figure, Axes]:
    """Create a horizontal bar plot with optional Chinese font support.

    Args:
        categories: Category labels for the y-axis.
        values: Numeric values for bar lengths.
        title: Plot title.
        xlabel: X-axis label.
        ylabel: Y-axis label.
        color: Single color for bars. If None, uses default palette.
        figsize: Figure size (width, height).
        font_path: Path to Chinese font file or directory. If provided, finds, registers and applies it.
        **kwargs: Extra arguments passed to axes.barh().

    Returns:
        Tuple of (Figure, Axes).
    """
    if len(categories) != len(values):
        raise ValueError("categories and values must have the same length")

    font_family = setup_chinese_font(font_path) if font_path is not None else None

    fig, ax = plt.subplots(figsize=figsize)
    bar_kwargs: dict[str, Any] = {}
    if color is not None:
        bar_kwargs["color"] = color
    bar_kwargs.update(kwargs)
    ax.barh(categories, values, **bar_kwargs)
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if font_family:
        apply_chinese_font(font_family, axes=ax)

    plt.tight_layout()
    return fig, ax
