"""Freeze a small public subset of GWTC-3 (O3b) posterior samples and O3b BBH injections.

This step needs network access and h5py. Readers do not have to run it: its outputs are
committed under inputs/ and every later script only reads those files.

Usage:
  python freeze_public_subset.py --injection-file <endo3_bbhpop-...-1256655642-12905976.hdf5> \
      --event-list <GWOSC GWTC-3-confident eventapi JSON> --out inputs

Posterior files are read from Zenodo record 5546663 by HTTP range requests, so only the
posterior table of each event is transferred, not the whole file.
"""
import argparse
import csv
import hashlib
import json
from pathlib import Path

import numpy as np

ZENODO_PE = "https://zenodo.org/records/5546663/files/IGWN-GWTC3p0-v1-{name}_PEDataRelease_mixed_cosmo.h5?download=1"
PIPELINES = ["cwb", "gstlal", "mbta", "pycbc_bbh", "pycbc_hyperbank"]
SAMPLES_PER_EVENT = 1500
FOUND_INJECTIONS_KEPT = 20000
SEED = 60


def md5(path):
    return hashlib.md5(Path(path).read_bytes()).hexdigest()


def select_events(event_list):
    """O3b candidates with FAR < 1/yr and a secondary above 3 solar masses (GWOSC medians)."""
    events = json.loads(Path(event_list).read_text())["events"].values()
    chosen = [e for e in events if e["far"] is not None and e["far"] < 1 and e["mass_2_source"] > 3]
    return sorted(chosen, key=lambda e: e["commonName"])


def read_posterior(name):
    import fsspec
    import h5py

    with fsspec.open(ZENODO_PE.format(name=name), "rb", block_size=2**20,
                     client_kwargs={"headers": {"User-Agent": "generic-research-client"}}) as remote:
        with h5py.File(remote, "r") as handle:
            label = "C01:Mixed"
            if label not in handle or handle[label]["posterior_samples"].shape[0] < 2000:
                label = "C01:IMRPhenomXPHM"
            table = handle[label]["posterior_samples"][()]
    return label, table["mass_1_source"], table["mass_2_source"], table["redshift"]


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--injection-file", required=True)
    parser.add_argument("--event-list", required=True)
    parser.add_argument("--out", default="inputs")
    args = parser.parse_args()
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(SEED)

    manifest = {"seed": SEED, "events": [], "eventListMd5": md5(args.event_list)}
    with open(out / "o3b-bbh-posterior-samples.csv", "w", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow(["event", "mass_1_source", "mass_2_source", "redshift"])
        for event in select_events(args.event_list):
            name = event["commonName"]
            label, m1, m2, z = read_posterior(name)
            keep = rng.choice(len(m1), size=min(SAMPLES_PER_EVENT, len(m1)), replace=False)
            for index in np.sort(keep):
                writer.writerow([name, f"{m1[index]:.4f}", f"{m2[index]:.4f}", f"{z[index]:.5f}"])
            manifest["events"].append({"name": name, "label": label, "samplesInRelease": int(len(m1)),
                                       "samplesKept": int(len(keep)), "gwoscFarPerYear": event["far"]})
            print(name, label, len(m1))

    import h5py

    with h5py.File(args.injection_file, "r") as handle:
        attributes = {key: (value.item() if hasattr(value, "item") else value) for key, value in handle.attrs.items()}
        injections = handle["injections"]
        far = np.min([injections[f"far_{p}"][()] for p in PIPELINES], axis=0)
        found = np.flatnonzero(far < 1.0)
        kept = np.sort(rng.choice(found, size=FOUND_INJECTIONS_KEPT, replace=False))
        m1 = injections["mass1_source"][()][kept]
        m2 = injections["mass2_source"][()][kept]
        z = injections["redshift"][()][kept]
        pdf = (injections["mass1_source_mass2_source_sampling_pdf"][()] * injections["redshift_sampling_pdf"][()])[kept]
    with open(out / "o3b-bbh-found-injections.csv", "w", newline="") as handle:
        writer = csv.writer(handle)
        writer.writerow(["mass_1_source", "mass_2_source", "redshift", "draw_pdf_m1_m2_z"])
        for row in zip(m1, m2, z, pdf):
            writer.writerow([f"{row[0]:.4f}", f"{row[1]:.4f}", f"{row[2]:.5f}", f"{row[3]:.6e}"])
    manifest["injections"] = {
        "file": Path(args.injection_file).name,
        "md5": md5(args.injection_file),
        "foundCriterion": "minimum FAR over cwb, gstlal, mbta, pycbc_bbh, pycbc_hyperbank below 1 per year",
        "foundTotal": int(len(found)),
        "foundKept": FOUND_INJECTIONS_KEPT,
        "totalGenerated": int(attributes["total_generated"]),
        "effectiveTotalGenerated": float(attributes["total_generated"]) * FOUND_INJECTIONS_KEPT / len(found),
        "analysisTimeSeconds": int(attributes["analysis_time_s"]),
        "drawDistribution": {key: attributes[key] for key in ["min_mass1", "max_mass1", "pow_mass1", "min_mass2", "pow_mass2", "max_redshift", "pow_z"]},
    }
    for name in ["o3b-bbh-posterior-samples.csv", "o3b-bbh-found-injections.csv"]:
        manifest[name] = hashlib.sha256((out / name).read_bytes()).hexdigest()
    (out / "frozen-subset-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")


if __name__ == "__main__":
    main()
