#!/opt/conda/conda-bld/gimmemotifs_1683029645943/_h_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_p/bin/python
import argparse
import os
import sys
from io import StringIO

from gimmemotifs import __version__
from gimmemotifs.preprocessing import combine_peaks

if __name__ == "__main__":

    description = f"GimmeMotifs v{__version__} - combine_peaks"

    parser = argparse.ArgumentParser(description=description)

    parser.add_argument(
        dest="peaks",
        help="MACS2 summit or narrowPeak files",
        metavar="PEAK_FILES",
        nargs="*",
    )
    parser.add_argument(
        "-g",
        "--genome",
        dest="genome",
        required=True,
        help="Genome name or genome file",
        metavar="FILE",
    )
    parser.add_argument(
        "-w",
        "--window",
        metavar="INT",
        dest="window",
        type=int,
        help="Window size (default 200)",
        default=200,
    )
    parser.add_argument(
        "-s",
        "--scale",
        dest="scale",
        help="Scale summit values",
        action="store_true",
        default=False,
    )

    args = parser.parse_args()

    _exit = False
    for fname in args.peaks:
        if not os.path.exists(fname):
            print(f"File {fname} does not exist!", file=sys.stderr)
            _exit = True
    if _exit:
        sys.exit(1)

    df = combine_peaks(args.peaks, args.genome, args.window, args.scale)
    output = StringIO()
    df.to_csv(output, sep="\t", index=False, header=False)
    output.seek(0)
    print(output.read())
