"""Compare published observables and fitted masses without matching different apertures."""

from xcop_hydrostatic_masses import analyse_cluster


def compare_catalogues(observations, cluster_records):
    planck = observations["planck"]["rows"]
    lensing = observations["lensing"]["rows"]
    rows = []
    for record in cluster_records:
        cluster = record["cluster"]
        catalogue = planck[cluster]
        weak_lensing = lensing.get(cluster)
        redshift = record["header"]["redshift"]
        if abs(redshift - catalogue["redshift"]) > 0.0005:
            raise ValueError(f"Redshift mismatch between X-COP and PSZ2 for {cluster}")
        aperture = None if weak_lensing is None else 1000 * weak_lensing["apertureRadius500Mpc"]
        # X-COP Section 2.5 masks three Planck bins blurred by the survey beam.
        fitted = analyse_cluster(record, aperture_kpc=aperture)
        mask = analyse_cluster(record, aperture_kpc=aperture, excluded_inner_sz_points=3)
        unity = analyse_cluster(record, excluded_inner_sz_points=3, fit_scale=False)
        row = {
            "cluster": cluster,
            "publishedXcopMass500": fitted["publishedMass500"] / 1e14,
            "refittedHydrostaticMass500": fitted["mass500"] / 1e14,
            "profileBasedPlanckRelationMass500": fitted["mass500FromPlanckYMRelation"] / 1e14,
            "planckProxyMass500": catalogue["mass500"],
            "planckProxyErrorLower": catalogue["errorLower"],
            "planckProxyErrorUpper": catalogue["errorUpper"],
            "planckProxyToXcopRatio": catalogue["mass500"] / fitted["publishedMass500"] * 1e14,
            "allBinsScore": fitted["pressureFit"]["chiSquare"],
            "allBinsCount": fitted["pressureFit"]["points"],
            "cutSize": 3,
            "cutBinsCount": mask["pressureFit"]["points"],
            "cutMass500": mask["mass500"] / 1e14,
            "cutPressureScale": mask["pressureFit"]["szScaleFactor"],
            "cutScore": mask["pressureFit"]["chiSquare"],
            "cutUnitScaleMass500": unity["mass500"] / 1e14,
            "cutUnitScaleScore": unity["pressureFit"]["chiSquare"],
        }
        if weak_lensing is not None:
            fixed = mask["fixedAperture"]
            row.update({
                "lensingNfwMass500": weak_lensing["nfwMass500"],
                "lensingNfwError": weak_lensing["nfwMass500Error"],
                "lensingApertureMass500": weak_lensing["apertureMass500"],
                "lensingApertureErrorLower": weak_lensing["apertureMassErrorLower"],
                "lensingApertureErrorUpper": weak_lensing["apertureMassErrorUpper"],
                "matchedApertureMpc": weak_lensing["apertureRadius500Mpc"],
                "publishedXcopMassAtLensingAperture": fixed["publishedHydrostaticMass"] / 1e14,
                "refitMassAtLensingAperture": fixed["fittedHydrostaticMass"] / 1e14,
                "matchedXcopToLensingRatio": fixed["publishedHydrostaticMass"] / (1e14 * weak_lensing["apertureMass500"]),
            })
        rows.append(row)
    return rows
