"""Recover the reported search FAR for each already-frozen O3b injection."""

import argparse
import csv
from pathlib import Path

import h5py
import numpy as np

from freeze_public_subset import PIPELINES
from frozen_inputs import INPUTS, load_found_injections, load_manifest, sha256

INJECTION_SHA256 = "ac194f6360534066d8e455dab8dca98651edf6fd52e423d1ef43bc21b38ff6a6"


def extract(path):
    manifest = load_manifest()
    if sha256(path) != INJECTION_SHA256:
        raise ValueError("Unexpected SHA-256 for LVK O3b T2100113 file")
    random = np.random.default_rng(manifest["seed"])
    for event in manifest["events"]:
        # Recreate the RNG state just before the original found-injection draw.
        random.choice(event["samplesInRelease"], event["samplesKept"], replace=False)
    with h5py.File(path, "r") as archive:
        records = archive["injections"]
        far = np.min([records["far_" + pipeline][:] for pipeline in PIPELINES], axis=0)
        found = np.flatnonzero(far < 1)
        release = manifest["injections"]
        assert int(archive.attrs["total_generated"]) == release["totalGenerated"]
        assert len(found) == release["foundTotal"]
        kept = np.sort(random.choice(found, size=release["foundKept"], replace=False))
        prior = records["mass1_source_mass2_source_sampling_pdf"][:] * records["redshift_sampling_pdf"][:]
        native = np.column_stack([records["mass1_source"][:][kept], records["mass2_source"][:][kept],
                                  records["redshift"][:][kept], prior[kept]])
        formats = (".4f", ".4f", ".5f", ".6e")
        frozen_rounding = np.asarray([[float(format(value, specifier)) for value, specifier in zip(row, formats)]
                                      for row in native])
        assert np.array_equal(frozen_rounding, load_found_injections()), "Frozen coordinate/prior rows differ"
        return np.column_stack([kept, far[kept]])


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("archive", type=Path)
    parser.add_argument("--out", type=Path, default=INPUTS / "o3b-bbh-found-far.csv")
    args = parser.parse_args()
    rows = extract(args.archive)
    with args.out.open("w", newline="") as handle:
        writer = csv.writer(handle, lineterminator="\n")
        writer.writerow(["release_row_index", "min_far_per_year"])
        writer.writerows((int(index), format(far, ".17g")) for index, far in rows)
    print(args.out.name, len(rows), sha256(args.out))


if __name__ == "__main__":
    main()
