#!/usr/bin/env python3
"""Top-level wrapper: run check_tier{1,2,3}.py in sequence (Plan 5 Task 4).

Subprocess-each strategy chosen over in-process import so that:
  - per-tier checks remain runnable standalone (single source of truth);
  - per-tier exit codes propagate naturally;
  - tier scripts can evolve independently without touching this wrapper.

Exits 0 only if all three tier checks PASS. Each tier's own PASS/FAIL
lines stream through to stdout so the top-level summary is auditable.
"""
from __future__ import annotations

import argparse
import os
import subprocess
import sys


HERE = os.path.dirname(os.path.abspath(__file__))
TIER_SCRIPTS = (
    "check_tier1.py",
    "check_tier2.py",
    "check_tier3.py",
)


def main():
    ap = argparse.ArgumentParser(
        description="Run all three tiered exit checks (Plan 5 Task 4).",
    )
    ap.add_argument(
        "metrics_json",
        help="Aggregated metrics JSON (output of aggregate-multi-seed-metrics.py).",
    )
    ap.add_argument(
        "--warmup-end",
        type=int,
        default=15,
        help="Epoch at which warmup ends; forwarded to each tier check.",
    )
    args = ap.parse_args()

    overall_ok = True
    for script in TIER_SCRIPTS:
        path = os.path.join(HERE, script)
        print(f"=== {script} ===")
        result = subprocess.run(
            [
                sys.executable,
                path,
                args.metrics_json,
                "--warmup-end",
                str(args.warmup_end),
            ],
            check=False,
        )
        if result.returncode != 0:
            overall_ok = False
            print(f"--- {script}: FAIL (exit {result.returncode}) ---")
        else:
            print(f"--- {script}: PASS ---")

    if overall_ok:
        print("ALL TIERS PASS")
        sys.exit(0)
    print("ONE OR MORE TIERS FAILED")
    sys.exit(1)


if __name__ == "__main__":
    main()
