"""Utility functions for the DataProducts model."""

from .ident import ArrayElementClass, DataType
from .reference import Product

__all_ = ["acada_filename"]


def acada_filename(
    product: Product,
    suffix: str = ".fits.fz",
    ae_class: ArrayElementClass | None = None,
) -> str:
    """
    Generate ACADA-style filename from metadata.

    Format from the ACADA-DPPS ICD, p17 is:
    <ae_ or sub_id>_<data_source_id>_<date or date time>_<?sb_id>
    _<?obs_id>_<?local_run_id>_<?type>_<?subtype>_<?increment>.<extension>
    """
    data_type_subtype_map = {
        DataType.AIRSHOWER: "SHOWER",
        DataType.MUON_CANDIDATE: "MUON",
        DataType.CALIBRATION: "CALIB",
    }

    # generate filename
    fname = []

    # array elements use a ae_id and ae_class:
    if product.instance.ae_id:
        if not (product.instance.ae_class or ae_class):
            raise ValueError(
                "ACADA filenames need an `ae_class` to be specified in the meadata or"
                " when calling this function."
            )
        # use metata for ae_class if it's there
        ae_class = product.instance.ae_class if product.instance.ae_class else ae_class
        fname.append(f"{ae_class}{product.instance.ae_id:03d}")

    # instead, if there is a subarray_id, use that
    elif product.instance.subarray_id:
        fname.append(f"SUB{product.instance.subarray_id:03d}")

    # data_source_id
    fname.append(str(product.instance.data_source))
    # date/time
    fname.append(product.creation_time.datetime.strftime("%Y%m%dT%H%M%S"))
    # optional sb_id
    if product.acquisition:
        fname.append(f"SBID{product.acquisition.sb_id:010d}")
    # optional obs_id
    if product.instance.obs_id:
        fname.append(f"OBSID{product.instance.obs_id}")
    # optional local_run_id

    # optional type (is it really optional? We always have it)
    fname.append(f"{product.data.association.upper()[:3]}")

    # optional subtype
    if product.data.type in data_type_subtype_map:
        fname.append(data_type_subtype_map[product.data.type])

    # optional chunk increment
    if product.instance.chunk_id:
        fname.append(f"CHUNK{product.instance.chunk_id:03d}")
    return "_".join(fname) + suffix
