from __future__ import annotations

import json
from pathlib import Path

import pandas as pd

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


def load_json(path: Path) -> dict:
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def fmt_float(value, digits: int = 4) -> str:
    try:
        return f"{float(value):.{digits}g}"
    except Exception:
        return str(value)


def main() -> None:
    print("RBFL / RBFT SPARC reproducibility quick check")
    print("=" * 56)

    clean_manifest = load_json(ROOT / "outputs/01_clean_sparc/sparc_clean_manifest.json")
    phase_summary = load_json(ROOT / "outputs/02_phase_tuner/phase_tuner_summary.json")
    corr_path = ROOT / "outputs/03_phase_correlations/phase_structure_correlations.csv"
    corr = pd.read_csv(corr_path)

    print("\nSPARC parse")
    print(f"  Galaxy-level rows:        {clean_manifest.get('Table1_rows')}")
    print(f"  Radial mass-model rows:   {clean_manifest.get('Table2_rows')}")
    print(f"  Merged radial rows:       {clean_manifest.get('merged_rows')}")
    print(f"  Overlap galaxies:         {clean_manifest.get('overlap_galaxies')}")

    print("\nPhase detector")
    print(f"  Galaxies analyzed:        {phase_summary.get('galaxies_analyzed')}")
    print(f"  Reference galaxy:         {phase_summary.get('reference_galaxy')}")
    print(f"  chi2 <= 1:                {phase_summary.get('inside_tolerance_chi2_le_1')}")
    print(f"  chi2 <= 1.5:              {phase_summary.get('soft_inside_chi2_le_1p5')}")
    print(f"  Median chi2/dof:          {fmt_float(phase_summary.get('median_chi2_dof'), 4)}")

    target = "B_y_outer_minus_inner_lnPhi"
    psi = corr[(corr["predictor"] == "Psi_bar") & (corr["target"] == target)]
    if psi.empty:
        print("\nPhase-structure correlation")
        print("  Psi_bar row not found in phase_structure_correlations.csv")
    else:
        row = psi.iloc[0]
        print("\nPhase-structure correlation")
        print(f"  Predictor:                {row['predictor']}")
        print(f"  Target:                   {row['target']}")
        print(f"  N:                        {int(row['N'])}")
        print(f"  Spearman rho:             {fmt_float(row['spearman_r'], 4)}")
        print(f"  p-value:                  {fmt_float(row['spearman_p'], 4)}")

    fig = ROOT / "figures/phase_structure_Psi_bar_vs_By.png"
    print("\nCore figure")
    print(f"  {fig.relative_to(ROOT)}")
    print(f"  Exists:                   {fig.exists()}")

    print("\nInterpretation boundary")
    print("  This quick check reproduces the SPARC phase-drift / baryonic-structure result.")
    print("  It does not claim full cosmology, full Bullet convergence-map fitting, or real arc inversion.")


if __name__ == "__main__":
    main()
