"""Plot helpers — small, opinionated wrappers over matplotlib.

Each function is a pure helper: pass in a records / decoupling DataFrame, an
optional Axes, and get the populated Axes back so the caller can tweak titles,
add their own colors, save the figure, etc.

The package itself doesn't take a hard matplotlib dependency at import time;
matplotlib is imported lazily inside the functions so notebooks that never
plot still load the rest of `openrun` cleanly.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pandas as pd

from .model import fit_decoupling

if TYPE_CHECKING:  # pragma: no cover
    from matplotlib.axes import Axes


def plot_fit_decoupling(
    records: pd.DataFrame,
    *,
    segments: int = 2,
    ax: "Axes | None" = None,
    warmup_min: float = 5.0,
    cooldown_min: float = 2.0,
    min_speed_mps: float = 0.5,
) -> "Axes":
    """Bar chart of per-segment Pa:Hr decoupling for one activity's FIT records.

    Each bar is one segment's `decoupling_pct` from `fit_decoupling`. Two
    horizontal references are drawn — Friel's `< 5%` "developed" line and the
    `10%` "unsustainable" threshold — so a reader can place the run at a
    glance.

    Returns the matplotlib Axes the bars were drawn on; pass `ax=` to compose
    multiple plots in one figure.
    """
    import matplotlib.pyplot as plt

    dec = fit_decoupling(
        records,
        segments=segments,
        warmup_min=warmup_min,
        cooldown_min=cooldown_min,
        min_speed_mps=min_speed_mps,
    )
    if ax is None:
        _, ax = plt.subplots(figsize=(6, 3.5))

    if dec.empty:
        ax.text(0.5, 0.5, "no usable records", ha="center", va="center", transform=ax.transAxes)
        ax.set_axis_off()
        return ax

    xs = dec["segment"].to_numpy()
    ys = dec["decoupling_pct"].to_numpy()
    ax.bar(xs, ys, width=0.7, color="#264653", edgecolor="white")
    ax.axhline(0, color="black", lw=0.6)
    ax.axhline(5, color="#2a9d8f", ls=":", lw=1, label="Friel < 5% (developed)")
    ax.axhline(10, color="#e76f51", ls="--", lw=1, label="Friel > 10% (unsustainable)")
    ax.set_xticks(xs)
    ax.set_xticklabels([f"seg {int(s)}" for s in xs])
    ax.set_ylabel("decoupling (%)")
    ax.set_title(f"Pa:Hr decoupling — {segments} segments")
    ax.legend(loc="best", fontsize=8)
    return ax
