from __future__ import annotations

import argparse
import json
import pathlib
import subprocess
import sys
import time

ROOT = pathlib.Path(__file__).resolve().parents[1]


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--timeout", type=int, default=90)
    args = parser.parse_args()
    started = time.perf_counter()
    try:
        completed = subprocess.run([sys.executable, "run_all.py", "--evidence"], cwd=ROOT, text=True, capture_output=True, timeout=args.timeout)
        payload = {"passed": completed.returncode == 0, "exit_code": completed.returncode, "elapsed_seconds": round(time.perf_counter() - started, 3), "stdout_tail": completed.stdout[-2000:], "stderr_tail": completed.stderr[-2000:]}
    except subprocess.TimeoutExpired as exc:
        payload = {"passed": False, "failure": "TIMEOUT_OR_RECURSION", "elapsed_seconds": round(time.perf_counter() - started, 3), "stdout_tail": (exc.stdout or "")[-2000:] if isinstance(exc.stdout, str) else "", "stderr_tail": (exc.stderr or "")[-2000:] if isinstance(exc.stderr, str) else ""}
    print(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True))
    return 0 if payload["passed"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
