"""Calibrate a correlated ringdown start search against public off-source strain."""

import argparse
from dataclasses import dataclass
from hashlib import file_digest
import json
from pathlib import Path

import h5py
import numpy as np
import scipy
from scipy.linalg import cholesky, eigh, solve_triangular, toeplitz
from scipy.stats import chi2

FS = 4096
WINDOW = 132
N = WINDOW - 2
LAST_START = 28
BLOCK = 8
STRIDE = FS // 8
GPS = 1420877824
DURATION = 4096
EVENT = 1420878141.2
DRAW_COUNT = 180_000
SEED = 250114
SCALE = 1e21
ALPHA = 0.01
SCORE_GRID = np.arange(0.0, 64.125, 0.125)
RHO_GRID = np.arange(0.0, 6.01, 0.5)
CUTS = {
    "fixed": np.array([0]),
    "shortSparse": np.arange(0, 9, 4),
    "short": np.arange(9),
    "sparse": np.arange(0, LAST_START + 1, 4),
    "dense": np.arange(LAST_START + 1),
}
F_STEM = "_GWOSC_O4b_4KHZ_R1-1420877824-4096.hdf5"
BASE_URL = "https://gwosc.org/archive/data/O4b_4KHZ_R1/1420820480/"
SOURCE = "https://gwosc.org/eventapi/html/O4_Discovery_Papers/GW250114_082203/v1/"
BERTI = "https://pages.jh.edu/eberti2/ringdown/fitcoeffsWEB.dat"
O1_GPS = 1126257415
O1_EVENT = 1126259462.4
O1_SOURCE = "https://gwosc.org/eventapi/html/GWTC-1-confident/GW150914/v3/"
O1_BASE = "https://gwosc.org/eventapi/json/GWTC-1-confident/GW150914/v3/"
O1_STEM = "_GWOSC_4KHZ_R1-1126257415-4096.hdf5"
PINNED_SHA256 = {
    "H-H1" + F_STEM: "db0b394ff10573f0e86b484adc59f176307c53fdc5f5ba5109a898f712674889",
    "L-L1" + F_STEM: "d95a6ebf274800f48fd966caf9198d6e2f91928d50d339c0c592defee06e82c1",
    "H-H1" + O1_STEM: "8ef8b762cff53b422429c474b1e35a6d9bfa86f3ed0c0d3e855f599781390a27",
    "L-L1" + O1_STEM: "bdd2dca270ad5205355b35d1a0da764c3927650917d971a10ecc6113efe4ebf4",
}


def mode(f_fit, q_fit):
    mass_time = 68.1 * 4.925490947e-6
    spin_deficit = 1.0 - 0.68
    omega = (f_fit[0] + f_fit[1] * spin_deficit**f_fit[2]) / mass_time
    q = q_fit[0] + q_fit[1] * spin_deficit**q_fit[2]
    return float(omega / (2 * np.pi)), float(2 * q / omega)


MODES = np.array([
    mode((1.5251, -1.1568, 0.1292), (0.7000, 1.4187, -0.4990)),
    mode((1.3673, -1.0260, 0.1628), (0.1000, 0.5436, -0.4731)),
])


def templates():
    time = np.arange(WINDOW) / FS
    columns = []
    for freq, tau in MODES:
        envelope = np.exp(-time / tau)
        phase = time * (2 * np.pi * freq)
        columns.extend((envelope * np.cos(phase), envelope * np.sin(phase)))
    return np.stack(columns, axis=1)


SHAPE = templates()
DIFF = np.diff(SHAPE, n=2, axis=0)


@dataclass
class Strain:
    values: np.ndarray
    good: np.ndarray
    info: dict


def read_strain(inputs, prefix, expected_gps=GPS, stem=F_STEM, base=BASE_URL):
    name = prefix + stem
    path = inputs / name
    with path.open("rb") as f:
        digest = file_digest(f, "sha256").hexdigest()
    expected_digest = PINNED_SHA256.get(name)
    if expected_digest is not None and expected_digest != digest:
        raise ValueError(f"Data checksum differs for {name}.")
    with h5py.File(path, "r") as f:
        gps = int(f["meta/GPSstart"][()])
        duration = int(f["meta/Duration"][()])
        detector = f["meta/Detector"][()].decode()
        channel = f["strain/Strain"]
        assert gps == expected_gps and duration == DURATION
        assert detector == prefix[2:] and len(channel) == FS * duration
        assert abs(float(channel.attrs["Xspacing"]) - 1 / FS) < 1e-12
        values = channel[:] * SCALE
        quality = f["quality/simple"]
        labels = [value.decode() for value in quality["DQShortnames"][:]]
        flag = quality["DQmask"][:]
        assert len(flag) == duration and "DATA" in labels
        used = [label for label in ("DATA", "CBC_CAT1") if label in labels]
        good = np.isfinite(values).reshape(duration, FS).all(axis=1)
        for label in used:
            good &= (flag & (1 << labels.index(label))) != 0
    return Strain(values, good, {
        "name": detector, "url": base + name, "sha256": digest,
        "sampleRate": FS, "startGPS": gps, "seconds": duration,
        "quality": used, "goodSeconds": int(good.sum()),
    })


def block_sets(segments, guard_event=EVENT):
    eligible = np.logical_and(*[s.good for s in segments]).reshape(-1, BLOCK).all(axis=1)
    blocks = np.arange(DURATION // BLOCK)
    seconds = segments[0].info["startGPS"] + BLOCK * blocks
    eligible &= ((seconds + BLOCK <= guard_event - 32) | (seconds >= guard_event + 32))
    return {
        "weights": blocks[eligible & (blocks % 4 == 0)],
        "calibration": blocks[eligible & (blocks % 4 == 1)],
        "holdout": blocks[eligible & (blocks % 4 >= 2)],
    }


def estimate_acf(values, blocks, seconds):
    n_fft = int(seconds * FS)
    taper = np.hanning(n_fft)
    pieces = np.concatenate([
        np.diff(values[b * BLOCK * FS:(b + 1) * BLOCK * FS], n=2)[:((BLOCK * FS - 2) // n_fft) * n_fft]
        .reshape(-1, n_fft) for b in blocks
    ])
    spectra = np.abs(np.fft.rfft(pieces * taper)) ** 2 / np.sum(taper**2)
    count = len(spectra)
    # The periodogram median has this expected multiplicative bias for exponential ordinates.
    ranks = np.arange(1, (count - 1) // 2 + 1, dtype=float) * 2
    median_bias = 1 + np.sum(1 / (ranks + 1) - 1 / ranks)
    spectrum = np.median(spectra, axis=0) / median_bias
    acf = np.fft.irfft(spectrum, n_fft)[:N]
    if np.linalg.cond(toeplitz(acf)) > 1e11:
        raise ValueError("Finite-window covariance too ill-conditioned for this calculation.")
    return acf


def bank(acf):
    cov = toeplitz(acf)
    weights = np.zeros((N, LAST_START + 1, 2))
    for first in range(LAST_START + 1):
        low = cholesky(cov[first:, first:], lower=True)
        whitened = solve_triangular(low, DIFF[first:], lower=True)
        q, _ = np.linalg.qr(whitened)
        weights[first:, first, :] = solve_triangular(low.T, q[:, 2:], lower=False)
    return weights


def projected(differenced, weights):
    packed = weights.reshape(N, -1)
    return (differenced @ packed).reshape(-1, LAST_START + 1, 2)


def score(projections):
    return sum(np.sum(detector**2, axis=-1) for detector in projections)


def independent_checks(acf, weights, traces):
    cov = toeplitz(acf)
    w = weights.reshape(N, -1)
    assert np.max(np.abs(w.T @ DIFF[:, :2])) < 1e-7
    joint = w.T @ cov @ w
    blocks = joint.reshape(LAST_START + 1, 2, LAST_START + 1, 2)
    for i in range(LAST_START + 1):
        np.testing.assert_allclose(blocks[i, :, i, :], np.eye(2), atol=1e-7)
    fast = projected(np.diff(traces, n=2, axis=1), weights)
    for first in (0, 4, 8, 16, 28):
        low = cholesky(cov[first:, first:], lower=True)
        x = solve_triangular(low, DIFF[first:], lower=True)
        y = solve_triangular(low, np.diff(traces[:, first:], n=2, axis=1).T, lower=True)
        residual_one = y - x[:, :2] @ np.linalg.lstsq(x[:, :2], y, rcond=None)[0]
        residual_two = y - x @ np.linalg.lstsq(x, y, rcond=None)[0]
        slow = np.sum(residual_one**2 - residual_two**2, axis=0)
        expected = np.sum(fast[:, first, :]**2, axis=-1)
        np.testing.assert_allclose(slow, expected, atol=1e-7, rtol=2e-7)
        # Eigensystem whitening uses an independent factorization of the cropped covariance.
        eigenvalues, basis = eigh(cov[first:, first:])
        fsym = basis.T / np.sqrt(eigenvalues)[:, None]
        x2 = fsym @ DIFF[first:]
        y2 = fsym @ np.diff(traces[:, first:], n=2, axis=1).T
        r1 = y2 - x2[:, :2] @ np.linalg.lstsq(x2[:, :2], y2, rcond=None)[0]
        r2 = y2 - x2 @ np.linalg.lstsq(x2, y2, rcond=None)[0]
        np.testing.assert_allclose(np.sum(r1**2 - r2**2, axis=0), expected, atol=3e-5, rtol=3e-6)
    return joint


def gaussian(covariances, rng):
    projections = []
    for covariance in covariances:
        values, vectors = eigh(covariance)
        assert values[0] > -1e-7
        keep = values > 1e-10
        factor = vectors[:, keep] * np.sqrt(values[keep])
        projections.append((rng.standard_normal((DRAW_COUNT, keep.sum())) @ factor.T)
                           .reshape(-1, LAST_START + 1, 2))
    return score(projections)


def measure(segments, blocks, weights, delay=0, retain_traces=False):
    indices = np.arange(0, BLOCK * FS - WINDOW - 10 + 1, STRIDE)
    origins = (blocks[:, None] * BLOCK * FS + indices).ravel()
    groups = np.repeat(blocks // 4, len(indices))
    traces = [segment.values[origins[:, None] + np.arange(WINDOW) + shift]
              for segment, shift in zip(segments, [delay, 0])]
    projections = [projected(np.diff(trace, n=2, axis=1), w) for trace, w in zip(traces, weights)]
    return origins, groups, projections, traces if retain_traces else None


def maxima(scores):
    return {label: scores[:, cuts].max(axis=1) for label, cuts in CUTS.items()}


def thresholds(distributions):
    result = {}
    for label, sample in distributions.items():
        count = int(len(sample) * ALPHA)
        assert count > 0
        index = len(sample) - count
        result[label] = float(np.partition(sample, index)[index])
    return result


def curves(distributions):
    return {label: np.round((len(values) - np.searchsorted(np.sort(values), SCORE_GRID, side="left"))
                            / len(values), 7).tolist()
            for label, values in distributions.items()}


def tails(distributions, level):
    return {label: int((values >= level).sum()) for label, values in distributions.items()}


def paired_interval(distributions, groups, q, rng):
    keys = list(distributions)
    _, cluster = np.unique(groups, return_inverse=True)
    sizes = np.bincount(cluster)
    n_cluster = len(sizes)
    counts = np.array([np.bincount(cluster, weights=(distributions[k] >= q), minlength=n_cluster)
                       for k in keys])
    resamples = rng.integers(0, n_cluster, size=(8000, n_cluster))
    rates = counts[:, resamples].sum(axis=-1) / sizes[resamples].sum(axis=-1)
    i_fixed, i_tiny, i_short, i_sparse, i_dense = map(
        keys.index, ("fixed", "shortSparse", "short", "sparse", "dense"))
    return {
        "groups": n_cluster,
        "shortDenseMinusSparse": np.quantile(rates[i_short] - rates[i_tiny], [0.025, 0.975]).tolist(),
        "wideSparseMinusShortSparse": np.quantile(rates[i_sparse] - rates[i_tiny], [0.025, 0.975]).tolist(),
        "wideDenseMinusSparse": np.quantile(rates[i_dense] - rates[i_sparse], [0.025, 0.975]).tolist(),
        "wideDenseMinusShort": np.quantile(rates[i_dense] - rates[i_short], [0.025, 0.975]).tolist(),
        "wideSparseMinusShort": np.quantile(rates[i_sparse] - rates[i_short], [0.025, 0.975]).tolist(),
        "wideDenseMinusFixed": np.quantile(rates[i_dense] - rates[i_fixed], [0.025, 0.975]).tolist(),
        "wideDenseOverFixed": np.quantile(rates[i_dense] / rates[i_fixed], [0.025, 0.975]).tolist()
        if np.all(rates[i_fixed] > 0) else None,
    }


def power(projections, weights, cutoffs, fixed_by_start, rng):
    shifts = []
    for p, w in zip(projections, weights):
        response = np.einsum("nki,nj->kij", w, DIFF[:, 2:])
        theta = rng.uniform(0, 2 * np.pi, len(p))
        direction = np.c_[np.cos(theta), np.sin(theta)] / np.sqrt(len(weights))
        shift = np.einsum("kij,mj->mki", response @ np.linalg.inv(response[0]), direction)
        np.testing.assert_allclose(np.sum(shift[:, 0, :]**2, axis=-1), 0.5, atol=1e-10)
        shifts.append(shift)
    results = {label: [] for label in CUTS}
    late_fixed = []
    for rho in RHO_GRID:
        scores = score([p + rho * u for p, u in zip(projections, shifts)])
        samples = maxima(scores)
        late_fixed.append(np.sum(scores >= fixed_by_start, axis=0).tolist())
        for label, counts in results.items():
            counts.append(int(np.sum(samples[label] >= cutoffs[label])))
    return {"search": results, "fixedByStart": np.transpose(late_fixed).tolist()}


def observed_examples(origins, traces, scan, thresholds_real):
    candidates = np.flatnonzero((scan[:, 0] >= thresholds_real["fixed"]) &
                                (scan.max(axis=1) < thresholds_real["dense"]))
    special = int(candidates[0]) if len(candidates) else 0
    spaced = [int(i) for i in np.linspace(0, len(origins) - 1, 15, dtype=int) if i != special]
    indexes = [special] + spaced
    return [{
        "gps": GPS + int(origins[i]) / FS,
        "didactic": j == 0 and bool(len(candidates)),
        "traces": [trace[i].tolist() for trace in traces],
        "scores": scan[i].tolist(),
    } for j, i in enumerate(indexes)]


def correlation(joints):
    matrices = [j.reshape(LAST_START + 1, 2, LAST_START + 1, 2) for j in joints]
    return np.sum([np.sum(m**2, axis=(1, 3)) for m in matrices], axis=0) / (2 * len(matrices))


def principal(joint):
    count = LAST_START + 1
    blocks = joint.reshape(count, 2, count, 2).transpose(0, 2, 1, 3)
    values = np.linalg.svd(blocks, compute_uv=False)
    np.testing.assert_allclose(np.diag(values[:, :, 0], k=1), 1, atol=1e-7)
    assert np.all(values >= 0) and np.all(values <= 1 + 1e-7)
    return np.round(np.clip(values, 0, 1), 7).tolist()


def independent_epoch(inputs, q):
    segments = [read_strain(inputs, d, O1_GPS, O1_STEM, O1_BASE) for d in ("H-H1", "L-L1")]
    blocks = block_sets(segments, O1_EVENT)
    acf = [estimate_acf(det.values, blocks["weights"], 2.0) for det in segments]
    w = [bank(a) for a in acf]
    _, _, cal, _ = measure(segments, blocks["calibration"], w)
    _, group, held, traces = measure(segments, blocks["holdout"], w, retain_traces=True)
    for a, b, t in zip(acf, w, traces):
        principal(independent_checks(a, b, t[:12]))
    cal_cutoffs = thresholds(maxima(score(cal)))
    test = maxima(score(held))
    return {"source": O1_SOURCE, "data": [det.info for det in segments], "n": len(group),
            "countCalibration": len(cal[0]), "tails": tails(test, q), "thresholds": cal_cutoffs,
            "survival": curves(test),
            "intervals": paired_interval(test, group, q, np.random.default_rng(SEED + 1)),
            "equalTarget": {k: int((v >= cal_cutoffs[k]).sum()) for k, v in test.items()}}


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("--inputs", type=Path, required=True, help="Folder containing both official HDF5 files")
    cli.add_argument("--out", type=Path, required=True, help="Write the live module data JS here")
    cli.add_argument("--o1", action="store_true", help="Verify the same search on GW150914 off-source data")
    args = cli.parse_args()
    rng = np.random.default_rng(SEED)
    segments = [read_strain(args.inputs, d) for d in ("H-H1", "L-L1")]
    blocks = block_sets(segments)
    assert all(len(group) > 2 for group in blocks.values())
    print("Valid seconds:", [int(s.good.sum()) for s in segments],
          "blocks:", {k: len(v) for k, v in blocks.items()}, flush=True)

    white_acf = np.r_[6, -4, 1, np.zeros(N - 3)]
    white_bank = bank(white_acf)
    white_joint = independent_checks(white_acf, white_bank, rng.normal(size=(12, WINDOW)))
    # Original white samples with explicit constant and linear nuisance form an independent limit.
    test_traces = rng.normal(size=(12, WINDOW))
    trend = np.c_[np.ones(WINDOW), np.linspace(-1.0, 1.0, WINDOW), SHAPE]
    for first in (0, 8, 28):
        raw_q, _ = np.linalg.qr(trend[first:])
        slow = test_traces[:, first:] @ raw_q[:, -2:]
        fast = projected(np.diff(test_traces, n=2, axis=1), white_bank)
        np.testing.assert_allclose(np.sum(slow**2, axis=1), np.sum(fast[:, first]**2, axis=1), atol=1e-8)

    acf = [estimate_acf(s.values, blocks["weights"], 2.0) for s in segments]
    actual_banks = [bank(a) for a in acf]
    _, _, cal, _ = measure(segments, blocks["calibration"], actual_banks)
    origins, held_groups, held, traces = measure(segments, blocks["holdout"], actual_banks, retain_traces=True)
    joints = [independent_checks(a, b, t[:12]) for a, b, t in zip(acf, actual_banks, traces)]
    print("Verified direct fits; making Gaussian reference distributions", flush=True)
    gauss_white = maxima(gaussian([white_joint, white_joint], rng))
    gauss_colored = maxima(gaussian(joints, rng))
    cal_dist = maxima(score(cal))
    held_scan = score(held)
    held_dist = maxima(held_scan)
    cutoffs = thresholds(cal_dist)
    rank = len(cal[0]) - int(ALPHA * len(cal[0]))
    fixed_by_start = np.partition(score(cal), rank, axis=0)[rank]
    fixed_level = float(chi2.isf(ALPHA, 4))
    assert abs(np.mean(gauss_white["fixed"] >= fixed_level) - ALPHA) < 0.001
    assert abs(np.mean(gauss_colored["fixed"] >= fixed_level) - ALPHA) < 0.001

    # Check if meaningful sensitivity to fit weights or modest detector shift changes the comparison.
    short_psd = [bank(estimate_acf(s.values, blocks["weights"], 0.5)) for s in segments]
    _, _, alt, _ = measure(segments, blocks["holdout"], short_psd)
    _, _, shift, _ = measure(segments, blocks["holdout"], actual_banks, delay=10)
    loading = []
    for a in acf:
        adjusted = a.copy()
        adjusted[0] += eigh(toeplitz(a), eigvals_only=True)[-1] * 1e-9
        loading.append(bank(adjusted))
    _, _, loaded, _ = measure(segments, blocks["holdout"], loading)
    relative = origins / FS + GPS - EVENT
    half_results = {"beforeEvent": (relative < 0), "afterEvent": (relative >= 0)}
    print("Testing equal-error power and clustered variation", flush=True)
    record = {
        "version": 1, "event": "GW250114", "eventGPS": EVENT, "source": SOURCE,
        "modeSource": BERTI, "data": [s.info for s in segments], "units": "strain Ãƒâ€” 10^21",
        "fs": FS, "n": WINDOW, "lastStart": LAST_START, "modes": MODES.tolist(),
        "cuts": {k: v.tolist() for k, v in CUTS.items()},
        "alpha": ALPHA, "fixedLevel": fixed_level, "seed": SEED,
        "environments": {"numpy": np.__version__, "scipy": scipy.__version__, "h5py": h5py.__version__},
        "partition": {key: val.tolist() for key, val in blocks.items()},
        "counts": {"white": DRAW_COUNT, "colored": DRAW_COUNT, "calibration": len(cal_dist["fixed"]),
                   "real": len(origins)},
        "curveStep": float(SCORE_GRID[1]), "acf": {"white": white_acf.tolist(), "real": [a.tolist() for a in acf]},
        "covarianceConditions": [float(np.linalg.cond(toeplitz(a))) for a in acf],
        "thresholds": {"white": thresholds(gauss_white), "colored": thresholds(gauss_colored), "real": cutoffs},
        "tails": {"white": tails(gauss_white, fixed_level), "colored": tails(gauss_colored, fixed_level),
                  "real": tails(held_dist, fixed_level)},
        "survival": {"white": curves(gauss_white), "colored": curves(gauss_colored), "real": curves(held_dist)},
        "rho": RHO_GRID.tolist(),
        "fixedByStartThresholds": fixed_by_start.tolist(),
        "power": power(held, actual_banks, cutoffs, fixed_by_start, rng),
        "principal": {"white": principal(white_joint),
                      "real": [principal(j) for j in joints]},
        "intervals": paired_interval(held_dist, held_groups, fixed_level, rng),
        "robustness": {"halfSecondPSD": tails(maxima(score(alt)), fixed_level),
                       "shiftedHanford": tails(maxima(score(shift)), fixed_level),
                       "loadedCovariance": tails(maxima(score(loaded)), fixed_level)},
        "epochs": {label: {"n": int(mask.sum()), "tails": tails(maxima(held_scan[mask]), fixed_level)}
                   for label, mask in half_results.items() if mask.any()},
        "correlation": {"white": np.round(correlation([white_joint, white_joint]), 7).tolist(),
                        "colored": np.round(correlation(joints), 7).tolist()},
        "examples": observed_examples(origins, traces, held_scan, cutoffs),
    }
    if args.o1:
        print("Verifying the frozen search with independent O1 strain", flush=True)
        record["o1"] = independent_epoch(args.inputs, fixed_level)
    payload = json.dumps(record, ensure_ascii=True, separators=(",", ":"), allow_nan=False)
    args.out.write_text("globalThis.RINGDOWN_DATA = " + payload + ";\n", encoding="utf-8", newline="\n")
    print(json.dumps({k: record[k] for k in ("modes", "counts", "fixedLevel", "thresholds", "tails",
                                          "intervals", "robustness", "epochs")}, indent=2))
    chosen_strength = RHO_GRID.tolist().index(3.0)
    print("Power at SNR 3:", {k: v[chosen_strength] for k, v in record["power"]["search"].items()})
    print("Planned start delayed, power at SNR 3:",
          [row[chosen_strength] for row in record["power"]["fixedByStart"]])
    if args.o1:
        print("O1:", {k: record["o1"][k] for k in ("n", "tails", "thresholds", "equalTarget")})


if __name__ == "__main__":
    main()
