#!/usr/bin/env python3
"""Fit TFOpt to three CSV files and write the results, a run bundle and the regulatory readout.

Usage:
    python run_tfopt.py                                     # the synthetic example shipped with TFOpt
    python run_tfopt.py --input1 input1.csv --input3 input3.csv --input4 input4.csv --out results \\
        --time-points 4 8 15 30 60 120 240 480 960 --ms-time-points 0 0.5 0.75 1 2 4 8 16 30 60 120 240 480 960

The two time grids (minutes of input3's and input1's columns) are required with your own files: TFOpt has no built-in
time grid. Every other setting not given here has the default of ``tfopt.api.RunConfig``; no config.toml is needed.
"""
import argparse
from pathlib import Path

from tfopt import api
from tfopt.analysis import network_readout
from tfopt.bundle import check_bundle
from tfopt.examples import example_grids, example_inputs


def main():
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("--input1", type=Path, default=None, help="TF protein and phosphosite series CSV")
    p.add_argument("--input3", type=Path, default=None, help="mRNA series CSV")
    p.add_argument("--input4", type=Path, default=None, help="TF -> target edges CSV (Source, Target)")
    p.add_argument("--time-points", type=float, nargs="+", default=None, help="RNA times of input3's columns (min)")
    p.add_argument("--ms-time-points", type=float, nargs="+", default=None, help="MS times of input1's columns (min)")
    p.add_argument("--out", type=Path, default=Path("tfopt_results"), help="results folder")
    p.add_argument("--n-starts", type=int, default=4, help="multistart starts (TFOpt's default is 64)")
    p.add_argument("--prediction-transform", choices=["clip", "none", "softplus"], default="clip")
    p.add_argument("--plots", action="store_true", help="also draw the per-target and fit-analysis plots")
    args = p.parse_args()
    inputs = (args.input1, args.input3, args.input4)
    if all(x is None for x in inputs):
        example = example_inputs(args.out / "example_inputs")  # generated, not real data
        args.input1, args.input3, args.input4 = example["input1"], example["input3"], example["input4"]
        args.ms_time_points, args.time_points = example_grids()
    elif any(x is None for x in inputs) or args.time_points is None or args.ms_time_points is None:
        p.error("give --input1, --input3, --input4, --time-points and --ms-time-points (or none, for the example)")

    config = api.RunConfig(input1=args.input1, input3=args.input3, input4=args.input4, results_dir=args.out,
                           time_points=args.time_points, ms_time_points=args.ms_time_points,
                           n_starts=args.n_starts, prediction_transform=args.prediction_transform,
                           plots=args.plots, fit_analysis=args.plots)

    report = api.validate_inputs(config.input1, config.input3, config.input4, ms_time_points=config.ms_time_points,
                                 time_points=config.time_points)
    for row in report.checks.itertuples():
        print(f"[{row.status}] {row.check} {row.detail}")
    if not report.ok:
        raise SystemExit("the inputs do not pass the checks")

    result = api.run(config, progress=lambda done, total, o: print(f"  start {done}/{total} finished"))
    print(f"best objective {result.best_objective:.8g} (start {result.selected_start}; "
          f"{'accepted' if result.accepted else 'NOT accepted'})")
    print(result.kkt.conditions.to_string(index=False))

    readout = args.out / "readout"
    readout.mkdir(exist_ok=True)
    for name, table in network_readout(args.out).items():
        table.to_csv(readout / f"{name}.csv", index=False)

    check = check_bundle(result.bundle)
    print(f"workbook {result.workbook}")
    print(f"run bundle {result.bundle} ({'valid' if check.ok else 'INVALID'})")
    print(f"readout tables in {readout}")


if __name__ == "__main__":
    main()
