#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""run_all.py — Component 7 · orchestrator for the whole chain

Part of the Seed Longevity Lab's downloadable Python lab (site v0.17.0,
longevity.seedsofhawaii.org/scripts). Pure interdependence: calls the sibling scripts in order and passes files between them.

Standalone by design: the shared cores below are embedded verbatim in every
script of the suite, so this file has NO imports from its siblings and no
third-party dependencies.
Python 3.9+. Input: a raw completed-test CSV (one row per completed
germination test) OR the suite's normalized_assays.csv interchange file.

Scientific contract: the Longevity Lab developer handoff
(specification/02_ANALYSIS_CONTRACT). Numerically cross-validated against
the site's JS engine, against R-equivalent references, and against the
matching R script (this component ships in both languages) by the site's
test suite. Each component's page card at /scripts spells out exactly where
behavior differs from the archival workflow behind the published catalog.

Counts rule, everywhere: actual number sown/tested + number germinated are
required. Nothing in this suite ever assumes a sample size.
"""

import sys

# ============================ command line ============================
def main():
    import argparse, os, subprocess, sys as _sys
    ap = argparse.ArgumentParser(description=(
        "Component 7 — orchestrator. Runs the whole Longevity Lab chain on "
        "one raw CSV: normalize → RCI → formal survival (reusing the RCI "
        "thresholds file — the real contingency) → shared-Ki → model "
        "comparison → plots (skipped politely if matplotlib is absent). "
        "Each sibling script must sit in the same folder; each also runs "
        "alone — this script just wires the interdependencies."))
    ap.add_argument("input", help="raw completed-test CSV")
    ap.add_argument("-o", "--outdir", default="longevity_lab_output")
    ap.add_argument("--time-unit", choices=["days", "months", "years"])
    args = ap.parse_args()
    here = os.path.dirname(os.path.abspath(__file__))
    os.makedirs(args.outdir, exist_ok=True)
    tu = ["--time-unit", args.time_unit] if args.time_unit else []
    norm = os.path.join(args.outdir, "normalized_assays.csv")
    def run(script, argv, optional=False):
        path = os.path.join(here, script)
        if not os.path.exists(path):
            print(f"[SKIP] {script} not found next to run_all.py", file=_sys.stderr)
            return optional
        r = subprocess.run([_sys.executable, path] + argv)
        if r.returncode == 3 and optional:
            return True
        if r.returncode != 0:
            _sys.exit(r.returncode)
        return True
    run("longevity_normalize.py", [args.input, "-o", norm] + tu)
    run("longevity_rci.py", [norm, "-o", args.outdir])
    run("longevity_formal.py", [norm, "-o", args.outdir,
                                "--thresholds", os.path.join(args.outdir, "rci_accession_intervals.csv")])
    run("longevity_shared_ki.py", [norm, "-o", args.outdir])
    run("longevity_models.py", [norm, "-o", args.outdir])
    run("longevity_plots.py", [norm, "-o", os.path.join(args.outdir, "plots")], optional=True)
    print(f"\nComplete. Everything is under {args.outdir}/ — normalized assays, RCI results "
          "(overall vs at-recommended kept separate), formal survival results, shared-Ki "
          "comparisons, model comparison, and plots.")

if __name__ == "__main__":
    main()
