"""CSV export helper that flattens list-valued columns with | separators."""
import pandas as pd


def export_as_csv(res, file_name):
    """Write an ActivePathways result table to CSV.

    List-valued columns (overlap and Genes_* evidence columns) are pipe-joined
    to stay one line per term, matching the R version.
    """
    out = res.copy()
    list_cols = [c for c in out.columns if c == "overlap" or c.startswith("Genes_")]
    for col in list_cols:
        out[col] = out[col].apply(_join_pipe)
    out.to_csv(file_name, index=False)


def _join_pipe(value):
    """Collapse list values to a pipe-delimited string; pass scalars through."""
    if isinstance(value, (list, tuple)):
        return "|".join(str(v) for v in value)
    return value
