"""Command-line interface for running ActivePathways from the shell."""
import argparse

import pandas as pd

from .enrichment import active_pathways
from .export import export_as_csv


def parse_arguments():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description="Run ActivePathways enrichment analysis.")
    parser.add_argument("--scores", required=True)  # Path to a TSV with a row per gene
    parser.add_argument("--gmt", required=True)  # Path to a GMT pathway file
    parser.add_argument("--output", required=True)  # Output CSV path
    parser.add_argument("--gene_col", default="Gene")  # Column name to use as the gene index
    parser.add_argument("--cutoff", type=float, default=0.1)
    parser.add_argument("--significant", type=float, default=0.05)
    parser.add_argument("--merge_method", default="Brown")
    parser.add_argument("--correction_method", default="holm")
    parser.add_argument("--cytoscape_file_tag", default=None)
    parser.add_argument("--geneset_filter_min", type=int, default=5)
    parser.add_argument("--geneset_filter_max", type=int, default=1000)
    return parser.parse_args()


def main():
    """Entry point for the ``activepathways`` console script."""
    args = parse_arguments()
    scores_df = pd.read_csv(args.scores, sep="\t").set_index(args.gene_col)
    scores_df = scores_df.fillna(1.0)  # follow the documented convention for missing p-values

    res = active_pathways(
        scores=scores_df,
        gmt=args.gmt,
        cutoff=args.cutoff,
        significant=args.significant,
        merge_method=args.merge_method,
        correction_method=args.correction_method,
        cytoscape_file_tag=args.cytoscape_file_tag,
        geneset_filter=(args.geneset_filter_min, args.geneset_filter_max),
    )
    if res is None:
        # Still write an empty file so downstream pipelines see a deterministic output.
        pd.DataFrame(columns=["term_id", "term_name", "adjusted_p_val", "term_size", "overlap"]).to_csv(args.output, index=False)
        return
    export_as_csv(res, args.output)


if __name__ == "__main__":
    main()
