"""Latency plotting utilities."""

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.latency")

try:
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    _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_latency(
    df: "pd.DataFrame",
    *,
    ax: Optional[Any] = None,
    threshold_ms: float = 500,
    color_good: str = "#0ecb81",
    color_bad: str = "#f6465d",
    title: Optional[str] = None,
    figsize: tuple[float, float] = (12, 4),
) -> Any:
    """Plot latency time series from a DataFrame.

    Colors bars red when above the threshold.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with 'latency_ms' column.
    ax : matplotlib Axes, optional
    threshold_ms : float
        Latency threshold for coloring (default: 500ms).
    color_good : str
        Color for sub-threshold bars.
    color_bad : str
        Color for above-threshold bars.
    title : str, optional
    figsize : tuple

    Returns
    -------
    matplotlib Figure
    """
    _check_deps()
    if df is None or df.empty:
        raise PlotError("DataFrame is empty")
    if "latency_ms" not in df.columns:
        raise PlotError("DataFrame must contain 'latency_ms' column")

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

    latency = df["latency_ms"].dropna()
    colors = [color_bad if v > threshold_ms else color_good for v in latency.values]

    ax.bar(latency.index, latency.values, color=colors, width=0.8, alpha=0.7)
    ax.axhline(threshold_ms, color=color_bad, linestyle="--", linewidth=1, label=f"Threshold {threshold_ms}ms")
    ax.set_ylabel("Latency (ms)")
    ax.set_xlabel("Time")
    ax.legend()
    ax.grid(alpha=0.2, axis="y")
    if title:
        ax.set_title(title)
    if fig:
        fig.autofmt_xdate()
    return fig if fig else ax.get_figure()
