"""Quote plotting utilities using matplotlib."""

from __future__ import annotations

from typing import Any, Optional

from sd_api.exceptions import PlotError
from sd_api.logging import get_logger

logger = get_logger("plot.quote")

try:
    import matplotlib
    matplotlib.use("Agg")  # non-interactive backend by default
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    _HAS_MATPLOTLIB = True
except ImportError:
    _HAS_MATPLOTLIB = False

try:
    import pandas as pd
    _HAS_PANDAS = True
except ImportError:
    _HAS_PANDAS = False


def _check_deps() -> None:
    if not _HAS_MATPLOTLIB:
        raise PlotError("matplotlib is required. Install with: pip install sd-api[plot]")
    if not _HAS_PANDAS:
        raise PlotError("pandas is required. Install with: pip install sd-api[plot]")


def plot_quote_series(
    df: "pd.DataFrame",
    *,
    ax: Optional[Any] = None,
    title: Optional[str] = None,
    color_bid: str = "#0ecb81",
    color_ask: str = "#f6465d",
    figsize: tuple[float, float] = (12, 5),
) -> Any:
    """Plot bid/ask/mid price series from a DataFrame.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with 'bid', 'ask', 'mid' columns.
    ax : matplotlib Axes, optional
        Existing Axes to draw on.
    title : str, optional
        Plot title.
    color_bid : str
        Line color for mid price (default: green).
    color_ask : str
        Ask line color (default: red).
    figsize : tuple
        Figure size in inches.

    Returns
    -------
    matplotlib Figure
    """
    _check_deps()
    if df is None or df.empty:
        raise PlotError("DataFrame is empty")

    fig = None
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)

    if "mid" in df.columns:
        ax.plot(df.index, df["mid"], color=color_bid, linewidth=1.2, label="mid")
    if "bid" in df.columns:
        ax.plot(df.index, df["bid"], color=color_bid, linewidth=0.8, alpha=0.6, label="bid")
    if "ask" in df.columns:
        ax.plot(df.index, df["ask"], color=color_ask, linewidth=0.8, alpha=0.6, label="ask")

    ax.set_ylabel("Price")
    ax.set_xlabel("Time")
    ax.legend()
    ax.grid(alpha=0.2)
    if title:
        ax.set_title(title)
    if fig:
        fig.autofmt_xdate()
    return fig if fig else ax.get_figure()


def plot_bid_ask(
    df: "pd.DataFrame",
    *,
    ax: Optional[Any] = None,
    title: Optional[str] = None,
    figsize: tuple[float, float] = (12, 5),
) -> Any:
    """Plot bid-ask spread as a filled area chart."""
    _check_deps()
    if df is None or df.empty:
        raise PlotError("DataFrame is empty")

    fig = None
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)

    if "spread" in df.columns:
        ax.fill_between(df.index, df["spread"], alpha=0.4, color="#f0b90b", label="spread")
        ax.plot(df.index, df["spread"], color="#f0b90b", linewidth=1)

    ax.set_ylabel("Spread")
    ax.set_xlabel("Time")
    ax.legend()
    ax.grid(alpha=0.2)
    if title:
        ax.set_title(title)
    if fig:
        fig.autofmt_xdate()
    return fig if fig else ax.get_figure()


def plot_spread(
    df: "pd.DataFrame",
    *,
    ax: Optional[Any] = None,
    title: Optional[str] = None,
    color: str = "#f0b90b",
    figsize: tuple[float, float] = (12, 4),
) -> Any:
    """Plot the spread time series."""
    _check_deps()
    return plot_bid_ask(df, ax=ax, title=title or "Spread", figsize=figsize)
