"""
MSD module — Merge multiple .msd files into a single MiniSEED.
"""

import glob
import logging
import os

import obspy

logger = logging.getLogger(__name__)


def merge_msd_files(
    input_dir: str,
    output_path: str,
    pattern: str = "*.msd",
) -> "obspy.Stream":
    """Read all MSD files from *input_dir* and merge into one MiniSEED file.

    Parameters
    ----------
    input_dir : str
        Directory containing ``.msd`` files.
    output_path : str
        Destination path for the merged MiniSEED file.
    pattern : str
        Glob pattern to match input files (default ``*.msd``).

    Returns
    -------
    obspy.Stream
        The merged stream object.

    Raises
    ------
    FileNotFoundError
        If no files match the pattern.
    """
    filenames = sorted(glob.glob(os.path.join(input_dir, pattern)))
    if not filenames:
        raise FileNotFoundError(
            f"No files matching '{pattern}' found in {input_dir}"
        )

    logger.info("Found %d file(s) in %s", len(filenames), input_dir)

    st = None
    for fname in filenames:
        logger.debug("Reading %s", fname)
        if st is None:
            st = obspy.read(fname)
        else:
            st += obspy.read(fname)

    st.write(output_path, format="MSEED")
    logger.info("Merged stream saved to %s (%d traces)", output_path, len(st))
    return st
