"""stopfloor: how much compute could ANY early-stopping rule save on your traces?

For cohorts of trials that each ran to the end, a rule that (a) looks at every
trial up to report k and (b) never loses the eventual winner cannot cost less than
   sum_t cost_t(k)  +  min over winners w of (cost_w(end) - cost_w(k)).
This is the zero-overhead, perfect-hindsight floor. If your target savings is ABOVE
the ceiling this implies, no forecaster can reach it at that screen (impossible). If it
is below, it is only possible in hindsight: picking the winner from the prefix and
paying overhead are not counted.

Input (JSONL, one cohort per line):
  {"trials": {"id": {"errors": [e1..eN], "seconds": [cumulative_s1..cumulative_sN]}, ...},
   "incumbent_seconds": 123.4}      # optional: what your current scheduler billed for this cohort
Usage: python stopfloor.py cohorts.jsonl --screens 4 8 12 16 [--target 0.30]
       python stopfloor.py --demo
Savings are measured against incumbent_seconds when every cohort has it, otherwise
against full continuation (and the output says which). With --target T, each screen
reports "impossible" if T exceeds the ceiling; otherwise only "possible in hindsight"
(a forecaster still has to find the winner, and pay overhead).
"""
import argparse, json, random, sys
from math import fsum, isfinite


def validate(cohorts, screens, incumbents):
    for ci, c in enumerate(cohorts):
        if not c: raise ValueError(f"cohort {ci}: no trials")
        n = None
        for tid, t in c.items():
            e, s = t.get("errors"), t.get("seconds")
            if not e or not s or len(e) != len(s): raise ValueError(f"cohort {ci} trial {tid}: errors/seconds missing or different lengths")
            if n is None: n = len(e)
            if len(e) != n: raise ValueError(f"cohort {ci}: trials have different report counts")
            if not all(isinstance(x, (int, float)) and isfinite(x) for x in e + s): raise ValueError(f"cohort {ci} trial {tid}: nonfinite value")
            if s[0] <= 0 or any(b <= a for a, b in zip(s, s[1:])): raise ValueError(f"cohort {ci} trial {tid}: seconds must be positive and strictly increasing")
        for k in screens:
            if not 1 <= k < n: raise ValueError(f"screen {k} outside 1..{n - 1} for cohort {ci}")
    if incumbents is not None and any(not (isinstance(x, (int, float)) and isfinite(x) and x > 0) for x in incumbents):
        raise ValueError("incumbent_seconds must be positive finite for every cohort")


def floor_cost(trials, k):
    best = min(t["errors"][-1] for t in trials.values())
    prefix = fsum(t["seconds"][k - 1] for t in trials.values())
    tail = min(t["seconds"][-1] - t["seconds"][k - 1]
               for t in trials.values() if t["errors"][-1] == best)
    return prefix + tail


def report(cohorts, screens, incumbent=None, target=None):
    full = fsum(t["seconds"][-1] for c in cohorts for t in c.values())
    base = incumbent if incumbent else full
    out = {"cohorts": len(cohorts), "baseline": "incumbent_seconds" if incumbent else "full_continuation",
           "baseline_hours": base / 3600, "max_saving_by_screen": {}}
    if target is not None:
        out["target"] = target; out["verdict_by_screen"] = {}
    for k in screens:
        f = fsum(floor_cost(c, k) for c in cohorts)
        ceiling = 1 - f / base
        out["max_saving_by_screen"][k] = round(ceiling, 4)
        if target is not None:
            out["verdict_by_screen"][k] = ("impossible (target above ceiling, even with hindsight)"
                if target > ceiling else "possible in hindsight only; overhead and winner selection not counted")
    return out


def demo(n=200, width=5, horizon=60, seed=0):
    rnd = random.Random(seed)
    cohorts = []
    for _ in range(n):
        trials = {}
        for i in range(width):
            final, rate = rnd.uniform(0.05, 0.5), rnd.uniform(0.05, 0.3)
            errs = [final + (0.9 - final) * (2.718 ** (-rate * s)) + rnd.gauss(0, .005) for s in range(horizon)]
            errs[-1] = final
            trials[str(i)] = {"errors": errs, "seconds": [10.0 * (s + 1) for s in range(horizon)]}
        cohorts.append(trials)
    return cohorts


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("cohorts", nargs="?")
    p.add_argument("--screens", type=int, nargs="+", default=[4, 8, 12, 16])
    p.add_argument("--target", type=float, help="required fractional savings, e.g. 0.30")
    p.add_argument("--demo", action="store_true")
    a = p.parse_args()
    if a.demo:
        cohorts, inc = demo(), None
    elif a.cohorts:
        rows = [json.loads(l) for l in open(a.cohorts)]
        cohorts = [r["trials"] for r in rows]
        have = ["incumbent_seconds" in r for r in rows]
        if any(have) and not all(have): sys.exit("incumbent_seconds present on some cohorts but not all; supply it for every cohort or none")
        incs = [r["incumbent_seconds"] for r in rows] if all(have) else None
        inc = None
    else:
        sys.exit("give cohorts.jsonl or --demo")
    if a.cohorts and not a.demo: 
        try: validate(cohorts, a.screens, incs)
        except ValueError as err: sys.exit(f"invalid input: {err}")
        inc = fsum(incs) if incs else None
    print(json.dumps(report(cohorts, a.screens, inc, a.target), indent=1))
