#! /usr/bin/env python

import argparse
from glob import glob
from datetime import datetime
from datetime import timedelta
from runpynb import run_notebooks
from runpynb import print_or_quiet

PARSER = argparse.ArgumentParser(
    description="Run (and time) Jupyter notebooks silently in command-line."
)
PARSER.add_argument(
    "notebooks",
    nargs="*",
    default=glob("*.ipynb"),
    help="List of Jupyter notebooks (*.ipynb) to be run (default=all notebooks in path).",
)
PARSER.add_argument(
    "-t",
    "--timeout",
    type=int,
    default=3600,
    help="Seconds until a cell in the notebook timesout, which raises a Timeouterror exception (default is 3600 = 1 hr).",
)
PARSER.add_argument(
    "-s",
    "--sequence",
    action="store_true",
    help="Sequence implicit in notebook lists. If error occurs somewhere, stop entire pipeline.",
)
PARSER.add_argument(
    "-o",
    "--output",
    action="store_true",
    help='Save output as a separate notebook with "-out"-suffix (e.g. *-out.ipynb) instead of overwriting existing file.',
)
PARSER.add_argument(
    "-v",
    "--version",
    type=int,
    help="Version of notebook to return (Default=No conversion). Notebook will be converted if necessary.",
)
PARSER.add_argument(
    "-q",
    "--quiet",
    default=False,
    action="store_true",
    help="Be quiet and don't print messages (including run time). Caution: Does not suppress error messages",
)

ARGS = PARSER.parse_args()


print_or_quiet(f"{ARGS=}", quiet=ARGS.quiet)
start_time = datetime.now()
print_or_quiet(f"\nStart time: {start_time.strftime('%Y-%m-%d %H:%M:%S')}", quiet=ARGS.quiet)

print_or_quiet("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", quiet=ARGS.quiet)
run_notebooks(
    notebooks=ARGS.notebooks,
    timeout=ARGS.timeout,
    ver=ARGS.version,
    assequence=ARGS.sequence,
    output=ARGS.output,
    quiet=ARGS.quiet,
)


print_or_quiet(f"End time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", quiet=ARGS.quiet)
elapsed_time = datetime.now() - start_time
elapsed_time = elapsed_time - timedelta(microseconds=elapsed_time.microseconds)
print_or_quiet(f"Elapsed time: {elapsed_time} (hh:mm:ss)", quiet=ARGS.quiet)
