#!/usr/bin/env python3
"""One-command SPARC phase reproducibility entry point.

Runs only the minimal reviewer-facing SPARC test:
1. Parse the included SPARC tables.
2. Run the phase detector.
3. Run the baryonic-structure correlation.
4. Print the headline numbers.
"""
from __future__ import annotations
import os
import subprocess
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def run_step(label: str, args: list[str], timeout: int = 180) -> None:
    env = os.environ.copy()
    env.setdefault("OMP_NUM_THREADS", "1")
    env.setdefault("OPENBLAS_NUM_THREADS", "1")
    env.setdefault("MKL_NUM_THREADS", "1")
    env.setdefault("NUMEXPR_NUM_THREADS", "1")
    env.setdefault("MPLBACKEND", "Agg")
    print(f"\n=== {label} ===", flush=True)
    proc = subprocess.run(
        [sys.executable, "-u", *args],
        cwd=ROOT,
        env=env,
        timeout=timeout,
    )
    if proc.returncode != 0:
        raise SystemExit(f"Step failed: {label} (exit code {proc.returncode})")


def main() -> None:
    required = [
        ROOT / "data" / "raw" / "Table1.mrt.txt",
        ROOT / "data" / "raw" / "Table2.mrt.txt",
        ROOT / "scripts" / "01_make_clean_sparc.py",
        ROOT / "scripts" / "02_run_phase_tuner.py",
        ROOT / "scripts" / "03_run_phase_correlations.py",
    ]
    missing = [str(p.relative_to(ROOT)) for p in required if not p.exists()]
    if missing:
        raise SystemExit("Missing required files:\n" + "\n".join(missing))

    print("RBFL / RBFT minimal SPARC phase reproducibility run")
    print("Included SPARC files:")
    print("  data/raw/Table1.mrt.txt")
    print("  data/raw/Table2.mrt.txt")

    run_step("1. Parse included SPARC tables", ["scripts/01_make_clean_sparc.py", "--root", "."])
    run_step("2. Run SPARC phase detector", ["scripts/02_run_phase_tuner.py", "--root", "."])
    run_step("3. Run phase-structure correlation", ["scripts/03_run_phase_correlations.py", "--root", "."])
    run_step("4. Print reviewer quick check", ["run_quick_check.py"])

    print("\nDONE: minimal SPARC phase result reproduced.")
    print("Core output file: outputs/03_phase_correlations/phase_structure_correlations.csv")
    print("Core figure: figures/phase_structure_Psi_bar_vs_By.png")


if __name__ == "__main__":
    main()
