#!/usr/bin/env python3
from __future__ import annotations

import json
from pathlib import Path

import pandas as pd


def main():
    root = Path(__file__).resolve().parents[1]
    base = root / "original_package/RBFL_SPARC_Reproducibility_Verified_PRO"
    out_dir = root / "outputs/reproduced"
    out_dir.mkdir(parents=True, exist_ok=True)

    merged = pd.read_csv(base / "outputs/01_clean_sparc/sparc_merged_clean.csv")
    gal_summary = pd.read_csv(base / "outputs/01_clean_sparc/sparc_galaxy_summary_clean.csv")
    phase = pd.read_csv(base / "outputs/02_phase_tuner/phase_tuner_results.csv")
    point = pd.read_csv(base / "outputs/02_phase_tuner/phase_tuner_point_residuals.csv")

    # Column names are kept from the original package where possible.
    strict_col = "inside_tolerance_chi2_le_1"
    soft_col = "soft_inside_chi2_le_1p5"
    chi_col = "chi2_dof" if "chi2_dof" in phase.columns else None
    summary = {
        "sparc_clean_radial_rows": int(len(merged)),
        "sparc_clean_galaxies": int(gal_summary["Galaxy"].nunique() if "Galaxy" in gal_summary.columns else len(gal_summary)),
        "phase_tuner_galaxies": int(len(phase)),
        "phase_tuner_point_rows": int(len(point)),
        "strict_corridor_count": int(phase[strict_col].sum()) if strict_col in phase.columns else None,
        "soft_corridor_count": int(phase[soft_col].sum()) if soft_col in phase.columns else None,
        "median_chi2_dof": float(phase[chi_col].median()) if chi_col else None,
        "reference_gauge": "NGC7331",
    }
    (out_dir / "original_sparc_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    pd.DataFrame([summary]).to_csv(out_dir / "original_sparc_summary.csv", index=False)
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()
