"""
Plotting module — Embed ObsPy waveform plots into Matplotlib figures.
"""

import logging

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

logger = logging.getLogger(__name__)


def plot_stream(stream, fig=None, title=None):
    """Render an ObsPy Stream onto a Matplotlib Figure.

    Parameters
    ----------
    stream : obspy.Stream
        Stream to plot.
    fig : matplotlib.figure.Figure, optional
        An existing figure to draw on.  A new one is created if *None*.
    title : str, optional
        Super-title for the figure.

    Returns
    -------
    matplotlib.figure.Figure
        The figure containing the waveform axes.
    """
    n_traces = len(stream)
    if n_traces == 0:
        logger.warning("Empty stream, nothing to plot.")
        return fig

    if fig is None:
        fig = plt.figure(figsize=(10, 2.5 * n_traces))
    else:
        fig.clear()

    for i, tr in enumerate(stream, 1):
        ax = fig.add_subplot(n_traces, 1, i)
        times = tr.times("matplotlib")
        ax.plot(times, tr.data, linewidth=0.5, color="#1976D2")
        ax.set_ylabel(f"{tr.stats.channel}\n({tr.stats.station})", fontsize=9)
        ax.xaxis_date()
        ax.tick_params(axis="both", labelsize=8)
        fig.autofmt_xdate()

        # Light grid
        ax.grid(True, alpha=0.3)
        ax.set_xlim(times[0], times[-1])

    if title:
        fig.suptitle(title, fontsize=11, fontweight="bold")

    fig.tight_layout()
    return fig


def get_stream_info(stream) -> list[dict]:
    """Extract metadata from each trace in a stream.

    Returns
    -------
    list of dict
        One dict per trace with keys: network, station, location, channel,
        starttime, endtime, sampling_rate, npts, duration_s.
    """
    info = []
    for tr in stream:
        s = tr.stats
        info.append({
            "network": s.network,
            "station": s.station,
            "location": s.location,
            "channel": s.channel,
            "starttime": str(s.starttime),
            "endtime": str(s.endtime),
            "sampling_rate": s.sampling_rate,
            "npts": s.npts,
            "duration_s": round(s.endtime - s.starttime, 2),
        })
    return info
